CSS:在保持比例的同时用图像填充div [英] CSS: filling a div with an image while staying in proportion

查看:786
本文介绍了CSS:在保持比例的同时用图像填充div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题不是新的...但我认为也许与新的CSS3技术可能有解决方案。我找到此主题 -



我已经在IE9,Chrome 31和Opera 18中成功测试过了,但没有其他浏览器进行了测试。一如往常,您必须考虑您的特殊支持要求。


I know this question is not new … however I thought maybe with new CSS3 techniques there might be solution to this. 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.

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?

Thank you in advance.

解决方案

If I correctly understand what you want, you may leave the width and height attributes off the image to maintain aspect ratio and use flexbox to do the centering for you.

HTML

<div class="fill">
    <img ...>
</div>

CSS

.fill {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden
}
.fill img {
    flex-shrink: 0;
    min-width: 100%;
    min-height: 100%
}

jsFiddle here

I tested this successfully in IE9, Chrome 31, and Opera 18. But no other browsers were tested. As always you must consider your particular support requirements.

这篇关于CSS:在保持比例的同时用图像填充div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆