更改高度时保持图像宽高比 [英] Maintain image aspect ratio when changing height

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

问题描述

使用CSS flex box模型,如何强制图像保持其纵横比?

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

JS小提琴: http://jsfiddle.net/xLc2Le0k/2/

请注意,图像会拉伸或缩小以填充容器的宽度.很好,但是我们也可以拉伸或缩小 height 来保持图像比例吗?

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标签,如果您定义了一侧,那么将调整另一侧的大小以保持宽高比,并且默认情况下图像会扩展到其原始大小.

For img tags if you define one side then other side is resized to keep aspect ratio and by default images expand to their original size.

使用此事实,如果将每个img标签包装到div标签中,并将其宽度设置为父div的100%,则高度将根据您的期望的长宽比确定.

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/0o5tpbxg/

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

这篇关于更改高度时保持图像宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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