I’m trying to create the above layout with CSS, but can’t quite figure it out. Each 16×9 rectangle is an image. The layout needs to be responsive. Any overflow on the captions will be hidden, so they’ll always be 1 line.
https://9elements.com/blog/building-a-combined-css-aspect-ratio-grid/ got me most of the way there, however the addition of the captions seems to screw the math up, and I can’t figure out how to adjust for it.
EDIT: The below snippet is what I tried, but obviously it’s not correct. Because the column on the right has 2 captions and the left hand box has 1 caption, the aspect ratio of 48/18 is no longer correct. I think if I used a padding hack instead of aspect-ratio
I could use calc
to somehow account for the addition of the captions? But I don’t understand the math well enough to even know where to begin with that.
.row {
aspect-ratio: 48/18;
display: flex;
max-width: 50rem;
gap: 1rem;
}
.column {
aspect-ratio: 16/18;
display: flex;
flex-direction: column;
gap: 1rem;
}
.item {
height: 100%;
display: flex;
flex-direction: column;
}
.img {
aspect-ratio: 16/9;
height: 100%;
}
<div class="row">
<div class="item">
<img src="https://via.placeholder.com/1920x1080/eee?text=16:9" class="img" />
caption goes here
</div>
<div class="column">
<div class="item">
<img src="https://via.placeholder.com/1920x1080/eee?text=16:9" class="img" />
caption goes here
</div>
<div class="item">
<img src="https://via.placeholder.com/1920x1080/eee?text=16:9" class="img" />
caption goes here
</div>
</div>
</div>
3
Answers
You can do it using CSS Grid as below
You can try with ‘table’ element if you can use. It may help much, I guess.
The code would be like below;
This needs a little bit of algebra to find the widths of the larger image and the smaller ones.
The calculation depends on knowing 3 things: the overall width you want, this is called –w in the snippet, the height you want the caption spaces to be. This is called –c in the snippet and the gap between grid figures, –g.
Start by noticing the obvious:
w = w1 + w2 where w1, w2 are the widths of the bigger and smaller images respectively. [You can adjust further for border widths and/or gaps if you want]
And then noticing that the height of the bigger image is 2*height of a smaller image + caption height:
w19/16 = (2(w2*9/16)) + c
So we’ve got two simultaneous equations from which we can work out that:
w1 = (w + (c * 8 / 9)) * 2 /3
w2 = (w / 3) – (c * 16 / 27)
From these we can set up a CSS grid as in this snippet:
Note: I changed the HTML to replace the item divs with a figure element containing an img and a figcaption as that seemed more logical.