I need a grid with fixed amount of columns and rows. Each column and row are filled in completely. Each cell consists of two parts - image with fixed aspect ratio (same for all cells) and caption with fixed height. I need grid to fit to parent (analogous how background-size: contain works). So far I came up with solution, which only fits grid to match width of parent.
Note: in this example parent of grid is whole screen, in real case it can be any size independent of screen size (so we cannot use vw and vh units).
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 1fr);
padding: 15px;
gap: 15px;
}
.grid-child {
background-color: red;
}
.fixed-ratio {
aspect-ratio: 4/3;
background-color: orange;
}
.caption {
background-color: yellow;
}
<div class="grid">
<div class="grid-child"><div class="fixed-ratio"></div><div class="caption">1</div></div>
<div class="grid-child"><div class="fixed-ratio"></div><div class="caption">2</div></div>
<div class="grid-child"><div class="fixed-ratio"></div><div class="caption">3</div></div>
<div class="grid-child"><div class="fixed-ratio"></div><div class="caption">4</div></div>
<div class="grid-child"><div class="fixed-ratio"></div><div class="caption">5</div></div>
<div class="grid-child"><div class="fixed-ratio"></div><div class="caption">6</div></div>
</div>