How to keep image same height as text in a grid two column layout
Hey all! Been wracking my brain trying to figure this one out for a while...
I've been given a design to replicate which is a two column grid layout. Text on the left, image on the right. The catch is the image should always be the same height as the text on the left. It also has to use grid and not flexbox, because I have to rearrange the order of the image from mobile to desktop.
I went through a few solutions, and the closest I got was using contain: size on the image, and having its natural aspect-ratio create a box for it to live in. While this does work in Chrome and Safari, Firefox is broken.
Is there perhaps a better way of doing this that I'm not thinking of?
https://codepen.io/nqunnjku-the-scripter/pen/pvjmPYQ
17 Replies
have you tried using the image as a background instead?
Yes, and doesn't quite work as I want because then I lose the aspect ratio.
The only way background image would work is if I adjust my grid to
grid-template-columns: 1fr 1fr, and then have the image live within that space with background-size: contain, background-repeat: no-repeat and background-position: bottom right.
But this isn't ideal because now the grid doesn't know about the width of the image, and the text doesn't fill to fit that space.how do you lose the aspect ratio?
hi, I can fix that issue
🤔 with chatgpt?
how are you?
hungry
btw, dont forget the #📝rules
Probably not explaining this right, but it gives me this. While this does keep the aspect ratio of the image, the grid doesn't know about the aspect ratio anymore and the text is constrained to this space rather than being allowed to grow until it hits the image minus the gap

here is a crazy idea: why dont you use flex?
Wanted to, but I can't. The design for mobile places the image under the title, so I need to use grid to move it around
Suppose I could dupe the image but bleh
hum ...
how about you set the aspect ratio to the parent element?
and just do
1fr auto for the columns?Runs it into the same problem in firefox sadly
Seems to be a bug with firefox with aspect ratio in grid
you shouldnt do this, but, you can give it a width and height of 100%
and it shouldnt distort
Alright, just going with the background-image solution for now
This is actually gonna be fixed in the next version of firefox if anyone stumbles across the same kind of issue
1957244 - Enable the new multi-pass grid track sizing behavior in a...
RESOLVED (aethanyc) in Core - Layout: Grid. Last updated 2025-09-02.
that's actually interesting
It's a bit hacky, but with grid, if you use absolute positioning, it's positioned within it's assigned cells, so you can sort of get there, though it's not perfect...
https://codepen.io/kevinpowell/pen/QwjXNEv?editors=1100
The grid sizing algo is so strange because of the order it needs to do things in, it's easy to run into edge cases with it.