CSS3 Flexbox维持图像长宽比 [英] CSS3 Flexbox maintain image aspect ratio

查看:111
本文介绍了CSS3 Flexbox维持图像长宽比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用CSS弹性框模型,如何强制图像保持其长宽比?

Using the CSS flex box model, how can I force an image to maintain its aspect ratio?

JS Fiddle
http://jsfiddle.net/xLc2Le0k/2/

JS Fiddle http://jsfiddle.net/xLc2Le0k/2/

请注意,图像伸展或收缩以便填充容器的宽度。这很好,但是我们也可以通过拉伸或缩小高度来保持图片比例?

Notice that the images stretch or shrink in order to fill the width of the container. That's fine, but can we also have it stretch or shrink the height to maintain the image proportions?

HTML

<div class="slider">
    <img src="http://www.placebacon.net/400/300" alt="Bacn">
    <img src="http://www.placebacon.net/400/300" alt="Bacn">
    <img src="http://www.placebacon.net/400/300" alt="Bacn">
    <img src="http://www.placebacon.net/400/300" alt="Bacn">
</div>

CSS

.slider {
    display: flex;
}
.slider img {
    margin: 0 5px;
}


推荐答案

使用这个事实,如果你将每个img标签包装到div标签和设置它的宽度到100%的父div,然后高度将根据你想要的长宽比。

Using this fact if you wrap each img tag into div tag and set its width to 100% of parent div then height will be according to aspect ratio as you wanted.

http://jsfiddle.net/xLc2Le0k/15/

* {
    margin: 0;
    padding: 0;
}
.slider {
    display: flex;
}
.slider .slide img {
    width: 100%;
}

这篇关于CSS3 Flexbox维持图像长宽比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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