I am trying to implement a grid that displays some product items. All grid items of the grid should have the same height which I am able to accomplish with grid-auto-rows: 1fr;
. But now I also want to add a banner in between with the height of its content. Of course this does not work because of grid-auto-rows: 1fr;
. If I remove grid-auto-rows: 1fr;
or change it to grid-auto-rows: auto;
or grid-template-rows: 1fr;
the banner will have the height of its content, but the other gris items will have the height based on the row. The goal is that still all grid items and all rows in the grid should have the same height.
How can I implement that?
I created a codepen: codepen.io/dsalvia/pen/Podzrjr
The first product has 5 rows. The banner has 1 row and other products have 3 rows. I want to have all product items the height of the tallest product item. So in this case all product items should have the height of 5 rows. Only the banner should have the height of 1 row
This is my HTML:
<div class="product-list">
<div class="grid-item">
<!-- Product Item -->
</div>
<div class="grid-item">
<!-- Product Item -->
</div>
<div class="grid-item">
<!-- Product Item -->
</div>
<div class="grid-item banner" style="grid-row-start: 2">
<!-- Banner -->
</div>
<div class="grid-item">
<!-- Product Item -->
</div>
<div class="grid-item">
<!-- Product Item -->
</div>
<div class="grid-item">
<!-- Product Item -->
</div>
</div>
And the CSS:
.product-list{
display: grid;
gap: 2rem;
grid-auto-rows: 1fr;
grid-template-columns: repeat(3,1fr);
}
.product-list .grid-item.banner{
grid-row-start: 2;
grid-column: 1/-1;
}
This is what I get:Banner with same height as the product items
And this is what I want to have: Banner with height of its content
Does someone have an idea how I can accomplish that?
3
Answers
Try:
instead of:
As explained in here MDN grid-auto-rows, specifies the size of an implicitly-created grid row track or pattern of tracks.
Based on your edited description, that is still achieveable with using
grid-template-rows
to set second row asauto
. The third row and next can use implicit grid withgrid-auto-rows: 1fr
so if you have product item with height of 6 lines of text in the future, every grid item will match the tallest item.I take and modified your sample code to show you the result
Hope it helps and fit with your case.
Here is the closest to what you are looking for that I could find. But it is not ideal since it assumes the number of rows in a page is fixed (5 rows in this example).
If that’s not want you want, I hope you find better.