Consider the following styling:
.container { display: flex; width: 100vw;}.container > div { min-width: 20rem;}.container > img { object-fit: cover; height: 100vh; width: 100%;}
Given the following HTML body:
<div class="container"><img src="https://static.vecteezy.com/system/resources/previews/021/615/987/original/tv-signal-test-screen-retro-television-color-test-vector.jpg"><div> Hi mom!</div></div>
(https://jsfiddle.net/2jbxtyz7/)
The image that lives inside the container will now be resized according to the available space inside the parent container (which depends on the browser window in my example). When the window (and therefore the available space) gets smaller, the image will be cropped. However, even then, you can still always see the full height, from top top bottom, as only the sides get cropped.
When the window gets bigger, however, the image will increase in width. In order to keep the aspect ratio, top and the bottom of the image will be cropped. I don't want the top and the bottom of the image to be cropped – I'd rather like the image to stop growing when it has reached the width that keeps the aspect ratio given the set height.
This should be easy: I changed the width: 100%
to max-width:100%
, so the image should shrink when the available size gets smaller than the actual image size, but shouldn't grow when more than the actual image size is available, right?
https://jsfiddle.net/2jbxtyz7/1/
No! Changing width
to max-width
completely disables the width constraint: Instead of being cropped, the image will now overflow when less than its actual size is available!
How can the image overflow with a max-width: 100%
? Shouldn't width
and max-width
behave the same when "natural" width of the element is bigger than the given value?
I'm really confused by this – does anyone have an explanation?
Another thing I tried was setting the width to min(100%,auto)
, but the min
function doesn't seem to accept auto
as a parameter.
Does anyone see a way to get the behaviour we have with width: 100%
on small browser windows (the image gets cropped on the sides) while still preventing the image from growing past the horizontal size we set (so we can always see the images top and bottom)?
Update
I now solved my case using the CSS calc function: As I know the image's aspect ratio, I can set the width to min(100%, calc(100vh*{factor}))
, where 100vh
is the height I set and {factor}
needs to be replaced with the factor it takes to get your image's width from its height. Not beautiful, but it does the job :D