Breakout! CSS Style

June 2, 2022
css -tips

You have a container to restrict the width of your page, but you want some inner content to not be constrained! To break free! Easy.

For a while not I did not have a width constraint as part of my layout pages. I constrained the individual parts. This way, whenever I did want to have full width content (like a background color), I could easily do it. But this created a lot of duplication:

<div class="container">spectacular content here</div>
<div class="bg-red">spectacular CTA here</div>
<div class="container">spectacular content here</div>
<div class="bg-blue">spectacular CTA here</div>
<div class="container">spectacular content here</div>	

You see how I had to keep adding a div with a class called container to constrain and bring the content back and then go full width with some color? Sucks. After years of doing this, I was like, there's got to be a better way. Maybe CSS6 introduced something. Using a feature flag or something.

HA! This has probably been possible since cssv.5 (j/k it uses calc). I used my trust Bingoogler and found this precious piece of code:

.breakout-and-be-free { margin:0 calc(50% - 50vw); }

I am not exactly sure what is going in that particular piece of code. The first 0 is the top/bottom. The second one is calc(50% - 50vw) which is 50% of the width - 50 view width units which is equivalent to 50 of the width….what in tarnation is going on?!?! We end up with what we want. 

Bingoogler pointed me to a html - Break element out of container - Stack Overflow question with an answer with some versions and a Full Width Containers in Limited Width Parents | CSS-Tricks - CSS-Tricks version that is a little different. The non-accepted answer on SO did it for me, so I didn't test the others yet, but they are here for posterity.

This is a great trick and I cannot believe I took so long to do this instead of that crap I was doing before. Now I can:

<div class="container">
     spectacular content here
     <div class="breakout-and-be-free bg-red">spectacular CTA here</div>
     spectacular content here
     <div class="breakout-and-be-free bg-blue">spectacular CTA here</div>
     spectacular content here
</div>