I found this thread — How do you stretch an image to fill a <div> while keeping the image's aspect-ratio? — that is not entirely the thing that I want.
I have a div with a certain size and an image inside of it. I want to always fill-out the div with the image regardless if the image is landscape or portrait. And it doesn't matter if the image is cut-off (the div itself has overflow hidden).
So if the image is portrait I want the width
to be 100%
and the height:auto
so it stays in proportion. If the image is landscape I want the height
to be 100%
and the width to be
auto`. Sounds complicated right?
<div class="container">
<img src="some-image.jpg" alt="Could be portrait or landscape"/>
</div>
Since I don't know how to do it I simply created a quick image of what I mean. I can't even properly describe it.
So, I guess I'm not the first one asking this. However I couldn't really find a solution to this. Maybe there is some new CSS3 way of doing this - I'm thinking of flex-box. Any idea? Maybe it's even easier than I expect it to be?
Try this:
Hope this helps
You can use div to achieve this. without img tag :) hope this helps.
The only way I achieved the "best case" scenario described, was putting the image as a background:
It's a bit late but I just had the same problem and finally solved it with the help of another stackoverflow post (https://stackoverflow.com/a/29103071).
Hope this still helps somebody.
Ps: Also works together with max-height, max-width, min-width and min-height css properties. It's espacially handy with using lenght units like 100% or 100vh/100vw to fill the container or the whole browser window.
Consider using
background-size: cover
(IE9+) in conjunction withbackground-image
. For IE8-, there is a polyfill.