Resize image to max height of height: auto container - this seems like it should be easy.

Rather than trying to explain what I'm doing, here's a codepen: https://codepen.io/sheepman4267/pen/zYMvJbY I want the div to be the minimum height of the text it contains, and I want the image to grow/shrink with that. Logically, it seems to me like height: min-content on the div and height: auto on the image should do this, but it doesn't. Is there a pure CSS way to do this, or am I going to have to mess with JS?
3 Replies
Wolle
Wolle•2y ago
I am 99% sure background-image on your div is what you want. Set the image and control it with background-size/position/repeat/... (small tipp: do not use float, except when you know that you need it)
Kevin Powell
Kevin Powell•2y ago
height: min-content and height: auto might as well be the same thing (there is probably an exception out there, but in general, they'll do the same thing). Also, it's the default behavior, so no need to declare it. The thing is, an image has a height to it, so if you do div { height: min-content; } (or auto), it's just using the height of the image. What you're trying to accomplish is actually pretty complicated if you want to use a regular image, since the image has a height of it's own. As long as the image is taller than the text, it's a pretty tricky thing to solve. The only thing I can think of is to have an empty element with a background-image on it, like Wolle suggested. Without JS, we can't tell an element to shrink to be the same size as something else. With flex and grid, items will grow to match the height of their tallest sibling though, so we can take advantage of that 🙂 Here I did it with grid: https://codepen.io/kevinpowell/pen/OJaMVXE
sheepman
sheepmanOP•2y ago
Hmm. I'll mess around a bit more. Thanks!
Want results from more Discord servers?
Add your server