Controlling aspect ratios in css grid children?

Suppose I have markup like

<div style="display:grid">
<a>
<img src="200x300px.jpg">
</a>
<a>
<img src="100x500px.jpg">
</a>
<a>
<img src="200x200px.jpg>
</a>
</div>

How can I control the aspect ratio of both the <a> wrapper and the <img> inside?

Suppose I wanted to set all of the grid items to have a 3:2 aspect ratio with the images filling the container?

Questions:

  • do you want all the a elements to be the same size?
  • how do you want the images to fill their space? (By having bits of the images cut off?)

Yes. All images the same size. So if the images are all set to, say 3:2 aspect ratio then all of the images would be 3:2 regardless of their native aspect ratio, and anything longer/shorter would simply be cut off (based from the center).

1 Like

Okay, that’s quite easy then. Here’s an example you could adapt:

Just change the aspect ratio to 3:2 to get what you want. You don’t have to use the li setup, but it’s not a bad idea, give that it’s technically a list of items.

1 Like

That seems to work great! I haven’t learned a whole lot of HTML in a while. Is aspect-ratio somewhat new?

The only problem I’m having now is that if the grid container is allowed to fill the width of the viewport, it’s widith with the aspect-ratio css mentioned above will be in excess of the viewport…

Yes, it’s quite new, but well supported now, so safe to use.

That will be easy to control. But it would be best if you could make up a Pen like the one above to demonstrate the problem you’re having, as otherwise it’s not clear what’s going wrong.

Relatively new. The way things work is that we often hear about useful CSS properties / values long before browsers implement them. So, it’s been a known property for quite some time but it’s only recently something which my colleagues and myself have been able to start using due to the list of browsers we support. https://caniuse.com/?search=aspect-ratio

Here’s a page on my dev server that shows what’s going on.

Note, the images above the header (.lcp-gallery) that is wider than the viewport.

1 Like

You can fix that by adding display: block to the images. E.g.

.lcp-gallery.grid>a>img {
    height: 100%;
    -o-object-fit: cover;
    object-fit: cover;
    width: 100%;
    display: block; /* Add this */
}

Around CSS line 38.

1 Like