Fake centered fixed width

What: Say the background of your website is white and you want, for example, a different color header, full width, with content inside the header that’s contained at a lesser width, and centered. Common enough scenario and usually created with one HTML-element (div, section, …) at full width and with a colored background and one HTML-element (div, article, …) with a fixed width and centered, holding the content.

Well, what if you only had one HTML-element to work with and you wanted this effect?

How: Obviously, the only way to do this is with padding. Say you want the fixed width to be 960px and the top and bottom padding 1rem:

padding: 1rem calc(50vw - (960px/2));

Where: Sridhar Katakam Genesis and WordPress tutorials.

EDIT: I’ve found that in practice this does not reliably lead to an element with a width of 960px. vw of course is the width of the viewport, which does not take into account the overflow-y scrollbar. Since scrollbars don’t all have the same width, you can’t compensate for it. So, where possible, I’ve found this a more reliable solution:

padding: 1rem calc(50% - (960px/2));

And personally, I find this notation more intuitive:

padding: 1rem calc((100% - 960px) / 2);

Leave a Comment