How can I fill a div with an image while keeping i

2020-01-25 12:08发布

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 beauto`. 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.

enter image description here

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?

14条回答
看我几分像从前
2楼-- · 2020-01-25 13:06

This should do it:

img {    
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
}
查看更多
叛逆
3楼-- · 2020-01-25 13:07

Just fix the height of the image & provide width = auto

img{
    height: 95vh;
    width: auto;
}
查看更多
登录 后发表回答