Reputation: 2741
I'm wondering how css grids can make use of max-widths. In the old way, you'd use a container with wrapper class that'd set the margins.
With CSS grids, depending on how you create them, you no longer need to use containers and sometimes you have no where to add one.
I want the header to be full width, but I want the nav within it to have a max width of 80% of the screen's resolution and margin auto it, this code is similar to the way one would have done it with a wrapping container. The question is, how do I do the same with aside and main as they are not inside of a parent to set a max width with?
body {
display: grid;
grid-template-areas:
"header header"
"aside main";
grid-template-columns: 275px 1fr;
grid-template-rows: 1fr 1fr;
}
header {
grid-area: header;
border: solid 1px black;
}
header > nav {
max-width: 80%;
margin: auto;
border: solid 1px blue;
}
aside {
grid-area: aside;
}
main {
grid-area: main;
}
HTML
<html>
<body>
<header>
<nav>nav</nav>
</header>
<aside>aside</aside>
<main>main</main>
</body>
</html>
If I have to wrap them inside of a container, how will that affect the grid? If I set the max width on the html or body tag then how would I get a header that stretches the full width of the browser?
https://jsfiddle.net/6zd3o088/6/
Upvotes: 5
Views: 19700
Reputation: 115047
Think of this as a FOUR column grid of
grid-template-columns: 10% 275px 1fr 10%;
Then assign your elements per the revised grid-areas
grid-template-areas:
"header header header header"
". aside main .";
body {
display: grid;
grid-template-areas: "header header header header" ". aside main .";
grid-template-columns: 10% 275px 1fr 10%;
grid-template-rows: 1fr 1fr;
margin: 0;
padding: 0;
background: lightgrey;
}
header {
grid-area: header;
background:rebeccapurple;
}
header>nav {
max-width: 80%;
margin: auto;
background: lightblue;
}
aside {
grid-area: aside;
background: lightgreen;
}
main {
grid-area: main;
background: pink;
}
<header>
<nav>nav</nav>
</header>
<aside>aside</aside>
<main>main</main>
To use a max-width
with the nav
respecting the value we have to take the nav
out of the header so it becomes a grid-item. Then we can align it on the grid over the header.
Using minmax
for inner columns we can achieve the desired result
body {
display: grid;
grid-template-columns: 1fr minmax(auto, 100px) minmax(auto, 300px) 1fr;
grid-template-rows: 1fr 1fr;
margin: 0;
padding: 0;
background: lightgrey;
}
header {
grid-column: 1/-1;
grid-row: 1;
background: rebeccapurple;
}
nav {
grid-column: 2 / 4;
grid-row: 1;
background: lightblue;
}
aside {
grid-column: 2;
background: lightgreen;
}
main {
grid-column: 3;
background: pink;
}
<header></header>
<nav>nav</nav>
<aside>aside</aside>
<main>main</main>
Demo'd here using smaller column width for reference only. Amend the max figures as desired.
Upvotes: 7