My objective is to make images
have the same height of description
. Currently, images
can be much larger if the image src is very tall vertically:
article {
display: grid;
grid-template-areas: "title title" "images description";
resize: both;
overflow: hidden;
}
.title {
grid-area: title;
padding: 8px;
}
.images {
grid-area: images;
}
img {
display: block;
/* max-width: 100%; */
}
.description {
grid-area: description;
padding: 8px;
}
<article>
<div class="title">There are many other articles like this one on the page</div>
<div class="images">
<img alt="random image" src="https://i.sstatic.net/MB9ui48p.png">
<img alt="random image" src="https://i.sstatic.net/MB9ui48p.png">
</div>
<div class="description">The description of the thing. The description of the thing. The description of the thing. The description of the thing. The description of the thing. The description of the thing.</div>
</article>
Setting the CSS for img {max-width: 100%;}
gets me exactly what I want, as long as the image is not too big vertically. If the image is vertically big, then the .images
div gets expanded too much, to cover all of the 100% width image, and then it dwarfs the .description
div to the right of it.
Most answers I saw here in SO mention setting max-height: 100%
, but it makes no difference in my case. Others suggested putting img as background to a div, but this seems like a hack.
I tried making the .images
container a flexbox, but also made no difference in constraining the vertical size.
What worked best so far was setting img {max-height: 50vh}
, but it’s not exactly the same as making .images
have the same height of .description
.
2
Answers
Here’s a grid solution that uses container queries which allow the grid to ignore how large the images want to be:
width: calc(100cqw - 15px);
on your images sizes them to be as wide as their container minus the width of any scrollbar (you might need to adjust the 15px if it overflows in your testing)One way you can do it is like this, although with a small amount of description you’ll get a lot of space between image and text.
You could let the description take up more of that space if you like, or set the image to cover the whole space, but that often wouldn’t look very nice.
Edit: one limitation here is that you can only have one image in there. I’ve put in two, but they sit on top of each other. If you want multiple images in there, then this won’t work!