We all wrap our webpages in a wrapper, or containing div so we can set a max-width for the entire page, and to be able to center it. You know, with something like this:
.container {
max-width: 1200px;
margin: 0 auto;
}
Well, I got tired of constantly adding a <div class="container"> to everything, so I decided to get creative.
Why would you want to do this, you ask? A background color that extends to the edge of your screen, but not the content contained within, is the perfect example. You'd need that containing div to sit around the content.
My thought: Could a page's max-width be set in CSS within each full-width block of content, rather than via a containing div?
Sure enough, it is! I have never seen this example used in the wild, so I figured it was worth sharing to see if I'm missing something obvious, or if this is actually a pretty cool hack.
The concept: Allow padding to fill up all the available horizontal space, EXCEPT the maximum width of your content.
To better visualize, split your page vertically in half so we can measure padding for each side. So if your content should be max-width: 1200px, then half the width of content is 600px. Now that we have half the page, we know how much space to subtract from each side. Now we want the padding on both sides to provide half of 100% of the page, EXCEPT the width of the content. It's better described in CSS:
padding-left: calc(50% - 600px)
padding-right: calc(50% - 600px)
The code above allows 1200px of content and splits the rest of available page space for even padding. Since padding only shows up if there's space, the padding takes advantage of said space and disappears when it isn't there.
But now there's a problem: Our text butts up to the edge of the screen up until our max content width. No prob! Set an invisible border for the width of "outer padding" (we'd use margin but it doesn't let background colors outside of its bounding box), and as long as your box-sizing is set to border-box, you'll now effectively have padding "around" your padding. So:
box-sizing: border-box
border-left: solid transparent 2rem
border-right: solid transparent 2rem
So long, annoying extra markup!