r/css • u/Rafii2198 • 17h ago
Question How to properly scale images vertically in a container and preserve their right aspect ratio?
I want to write some custom CSS for a page I'm using, it has a custom CSS in its options so its really easy, but that means I can't do anything to HTML side of things, only CSS.
What I want to do is to make their media gallery wider and turn it into a carousel. Making the gallery wider also means I want to make the images there have increased height, as there is more real estate for them to fit it. The problem is that images and videos there are user submited and don't have a standardized aspect ratios or anything, everone can upload whatever they want. This is troubling me a bit as I don't know how to make it responsive, originally everything had set width and height in pixels, but I want to make it responsive, but no matter what I do, those images don't look right, sometimes they are clipped, sometimes they are massive and I was tweaking and tweaking it to the point I decided to ask for some help as nothing I do seems to work and no solution on internet helps me either, maybe I can't google who knows.
The HTML side of things basically looks like this: (The amount of content there is in card-media can very, from just 1 element to I think 50)
<div class="card">
...
<div class="card-media">
<img class="card-media-element" width="450" height="450">
<img class="card-media-element" width="450" height="253">
<img class="card-media-element" width="364" height="400">
</div>
</div>There is some already existing CSS, but it shouldn't really affect what I want, the only relevant thing that could be affecting it somehow is that card-media has position relative set and card-media-element has block-size set to auto (first time seeing this property personally, so I'm unsure what it does), but I tried to change or remove these, and nothing happened to the sizes of images. Other than that there is just text color, size, font and only stuff like that.
The CSS I wrote currently looks like this:
.card-media {
display: flex;
gap: 0.25rem;
max-width: 100%;
overflow-x: scroll;
scrollbar-width: thin;
overscroll-behavior-x: contain;
width: 100%;
height: 100%;
max-height: 26em;
padding: 0.25em;
}
.card-media-element {
object-fit: cover;
height: auto;
width: auto;
max-height: 50vh;
}The problem with this is that the images I am looking at are like zoomed in so I can't see them whole as they are like cropped, if I remove the object-fit then they are stretched, like square images become rectangular for some reason. What I want is to make all of them have the same height, and their width would be adjusted to the individual image aspect ratio. Basically I want to have consistent height of media in the card-media div, and their width can be however long it has to be, as it's overflowing anyway.
Is this possible?