I am trying to create a simple layout using CSS grid instead of flexbox:
https://i.sstatic.net/xjEy0m.jpg
Currently, I have something similar but with an unwanted white area:
https://i.sstatic.net/IEe2Wm.jpg
My question is, what am I missing in my code to achieve the desired layout?
The issue seems similar to these questions: How to make CSS Grid items take up remaining space?
And this one: How do you collapse unused row in a CSS grid?
However, it's a bit more complicated since I have an extra row
I have a green div on the last row that needs to grow with the page height.
To achieve that, the row template for this last row is set to 1fr
.
Here is my current code:
You can view the simple code snippet below:
html {
height: 100%;
}
body {
height: 100vh;
}
.container {
display: grid;
grid-template-columns: 180px 1fr;
grid-template-rows: min-content auto 1fr;
height:100%;
}
.red-cube {
background-color: red;
width: 100%;
Height: 180px;
grid-column: 1;
grid-row: 1 / 3;
}
h1, h2 {
margin: 0;
padding: 0;
}
.blue-title {
background-color: blue;
grid-column: 2;
grid-row: 1;
height: fit-content;
}
.yellow-div {
background-color: yellow;
grid-column: 2;
grid-row: 2;
height: 100%;
}
green-content {
background-color: green;
grid-column: 1 / 3;
grid-row: 3;
align-self: stretch;
}
<div class="container">
<div class="red-cube"></div>
<h1 class="blue-title">Title</h1>
<div class="yellow-div"><h2>Second line</h2></div>
<div class="green-content"><p>Some text</p></div>
</div>
Feel free to play around with the code snippet on Codepen here.
Attempted Solution:
I tried setting the grid-template-rows
value of the yellow row to 1fr
to fill the remaining space. However, this broke the green div that should grow with the page height as we would then have two rows with a setting of 1fr
.
In Conclusion:
I'm curious if there is a solution that doesn't involve switching to flexbox or restructuring the layout into multiple grid layouts.
I also want to avoid "hardcoding" the row heights by using something like:
grid-template-rows: 1.25rem auto 1fr;