SiteWebAstrolabe/src/posts/a-post-with-code-samples.md
2020-06-19 23:47:44 +02:00

3.3 KiB
Raw Blame History

title date tags
A post with code samples 2019-12-18
demo-content
code
blog

The best way to demo a code post is to display a real life post, so check out this one from andy-bell.design about a full bleed CSS utility.


Sometimes you want to break your components out of the constraints that they find themselves in. A common situation where this occurs is when you dont have much control of the container that it exists in, such as a CMS main content area.

This is even more the case with editing tools such as the WordPress Gutenberg editor, where in theory, you could pull in a component from a design system and utilise it in the main content of your web page. In these situations, it can be pretty darn handy to have a little utility that makes the element 100% of the viewports width and still maintain its flow within its parent container.

This is when I normally pull the .full-bleed utility class out of my back pocket.

The .full-bleed utility

Its small, but hella mighty:

.full-bleed {
  width: 100vw;
  margin-left: 50%;
  transform: translateX(-50%);
}

Here it is in a context where it makes a fancy <aside> and a <figure> element bleed out of their parent container.

The .full-bleed utility gives those elements prominence and importantly keeps their semantic place in the page. Just how I like it.


🔥 Pro tip: When working with a utility like .full-bleed, its a good idea to add an inner container that has a max-width and auto horizontal margin. For this, I normal create a shared .wrapper component like this:

.wrapper {
  max-width: 50rem;
  margin-left: auto;
  margin-right: auto;
}

Having a container like .wrapper helps to create consistent, centred content.


How the .full-bleed utility works

We set the container to be width: 100vw, which equates to the full viewport width. We couldnt set it to width: 100% because it would only fill the space of its parent element. The parent elements width is useful though, because by setting margin-left: 50%, we are telling the component to align its left edge to the center of its parent element, because 50% is half of the parent elements width.

Finally, we use CSS transforms to translateX(-50%). Because the transform works off the elements dimensions and not the parents dimensions, itll pull the element back 50vw, because its 100vw wide, thus making it sit perfectly flush with the viewports edges.

Wrapping up

Hopefully this short and sweet trick will help you out on your projects. If it does, drop me a tweet, because Id love to see it!