CSS grid does not fit its parent div's height
12,214
You have to set an explicit height for the grid container and then remove calc
from grid-template-rows
and make it 1fr
for the second row.
So you can set height: 100%
for page
(so it inherits the height of container
) and use grid-template-rows: 55px 1fr
(the second row now expands to fit the remaining height). See demo below:
body {
margin: 0;
}
.container {
width: 70%;
height: 300px; /* How can I set the height? */
}
.page {
width: 100%;
height: 100%; /* added */
display: grid;
grid-template-rows: 55px 1fr; /* changed */
grid-template-columns: 200px auto;
grid-template-areas:
"nav header"
"nav content";
}
.nav {
grid-area: nav;
background-color: aqua;
}
.header {
grid-area: header;
background-color: grey;
}
.content {
grid-area: content;
background-color: red;
overflow-y: auto; /* overflow condition on parent */
}
article {
height: 1000px; /* height set on child; triggers scroll */
}
<div class="container">
<div class="page">
<div class="nav">Side nav</div>
<div class="header">Header</div>
<div class="content">
<article>
<!-- new section for content -->
<h1>title</h1>
<p>A lot of content, simulated by .article height: 1000px</p>
</article>
</div>
</div>
Related videos on Youtube
Author by
Greg Forel
Updated on June 04, 2022Comments
-
Greg Forel almost 2 years
I built a CSS grid layout with a header, a sider and some scrollable content.
I'm trying to test that layout in a container
div
where I'm setting thewidth
andheight
.The layout responds well to the container's
width
, but not to theheight
, why is that and is there a way to fix it?body { margin: 0; } .container { width: 70%; height: 300px; /* How can I set the height? */ } .page { width: 100%; display: grid; grid-template-rows: 55px calc(100vh - 55px); /* height limitation on second row */ grid-template-columns: 200px auto; grid-template-areas: "nav header" "nav content"; } .nav { grid-area: nav; background-color: aqua; } .header { grid-area: header; background-color: grey; } .content { grid-area: content; background-color: red; overflow-y: auto; /* overflow condition on parent */ } article { height: 1000px; /* height set on child; triggers scroll */ }
<div class="container"> <div class="page"> <div class="nav">Side nav</div> <div class="header">Header</div> <div class="content"> <article> <!-- new section for content --> <h1>title</h1> <p>A lot of content, simulated by .article height: 1000px</p> </article> </div> </div>
-
Greg Forel about 5 yearsThe
fr
unit was a much better choice indeed, thank you! Is that always a better choice to usefr
instead ofauto
? I'm wondering if I should also write:grid-template-columns: 200px 1fr;