I am using css grid, when I resize the window, the two divs inside the container will be responsive where it goes from 2 divs in a row to 1 div per row.
My 1st div is wider than the 2nd div, 4 span version 2 span. Here is where I am stuck. When I resize the window, the 2nd div moves below the 1st div, but I want both to be equal width. The 1st div occupies 100% of the first row, but the 2nd div occupies 25% of 2nd row. How can I make them both occuping 100% of the row when they are stacked on top of each other?
HTML
<div class="myContainer">
<div class="area1">
...
</div>
<div class="area2">
...
</div>
</div>
CSS
.myContainer {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(175px, 1fr));
}
.myContainer > div:first-child {
grid-column: span 4; // make my first div container wider than 2nd div container
}
.myContainer > div:nth-child(2){
grid-column: span 1; // set the width of my 2nd div container
}
When the page first loads, it looks good, width of 1st div container is wider than 2nd div container.
I shrink the width of the window, the 2nd div container is stacked under the 1st div container but the width remains much smaller. I think it is still set at span 1.
I tried the following
// added span-4
…
// in the css
@media (min-width: 175px) {
.span-4 {
grid-column: span 4; // no luck here
}
}
.area {
width: 100%;
}
Any help is greatly appreciated. Thanks in advance. a
2
Answers
To make both the divs occupy 100% of the row when they are stacked on top of each other, you can use the grid-template-rows property. Set it to auto for the first row and 1fr for the second row. This will make the first row take the height it needs to fit the content, and the second row to take up the remaining space in the grid.
Here is the updated CSS:
You may need to adjust the grid-template-columns value based on your desired layout and the size of your container.
The constraints imposed equate to the grid becoming a single column when the width is 700px or less.
This snippet therefore does not alter the spans of the children, but sets the grid to be two columns 4fr 1fr initially and resets it to a single column when the viewport shrinks to 700px or less.