I have a classic site set-up with a header, main content with sidebar, and a footer. On wider screens I want the header and footer to be full width, while the main and sidebar have a fixed width, with whitespace on either site. When you make the screen narrower the whitespace shrinks (much like here at StackExchange). Once you reach the main+sidebar width, these scale down. In the old days, I would put a wrapper around main+sidebar, apply max-width:1200px; margin:0 auto;
and it was done. Now I'm trying to solve this with grid
, but to no avail. Here's the code:
<div id="totalcontent">
<div id="header">content</div>
<div id="main">content</div>
<div id="sidebar">content</div>
<div id="footer">content</div>
</div>
<style>
#totalcontent {
grid-template-areas:
'header header'
'main sidebar'
'footer footer';
grid-template-columns: 66% auto;
}
</style>
Now, I can put (say) max-width:900px; float:right
on #main
and max-width:300px; float:left;
on #sidebar
to make them narrower, but only when window width is 1800px
will this lead to neatly centered content with 300px
whitespace on either side. As soon as the screen becomes narrower, main+sidebar veer left, because at 1500px
width you would need grid-template-columns: 70% auto;
to have 150px
whitespace on either side.
What I tried
- Make it a four column grid with empty blocks either side of main and sidebar. Tried all kinds of things with
grid-template-columns
to prioritize the empty blocks shrinking. No luck. - Use media queries to adjust
grid-template-columns
. That worked, but made the design jumpy when dragging the window to resize it. - Ditch the grid system and revert to css plus added html. This works, but looks hacky.
The latter solution looks like this:
<div id="totalcontent">
<div id="header">content</div>
<div id="main"><div class="inner">content</div></div>
<div id="sidebar"><div class="inner">content</div></div>
<div id="footer">content</div>
</div>
<style>
#main {width:calc( 900px + ( (98vw - 1200px) / 2) );}
#main .inner {max-width:900px; float:right}
#sidebar {width:calc( 300px + ( (98vw - 1200px) / 2) );}
#sidebar. inner {max-width:300px; float:left;}
</style>
<!-- 98vw instead of 100vw as a safety margin to account for gap -->
Question
The problem seems to be that you can center a single grid item inside a row using justify-content:center;
but you cannot center multiple grid items inside a row. Is that correct? If not, how do I do it?