Html 强制图像适合并保持纵横比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34713763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force an image to fit and keep aspect ratio
提问by Sebastian Hernandez
I want an image to fill the 100% of its container's width, and I want it to have a max-heigth property set to it, all this keeping the aspect ratio but allowing to lose any part of the image.
我想要一个图像填充其容器宽度的 100%,并且我希望它设置一个 max-heigth 属性,所有这些都保持纵横比但允许丢失图像的任何部分。
img {
max-height:200px;
width:100%;
}
I know a similar thing can be done with background-size
property but i want to make this to an inline <img>
tag.
我知道可以用background-size
属性来做类似的事情,但我想把它变成一个内联<img>
标签。
Any idea of how could i achieve this using CSS? or javascript?
知道如何使用 CSS 实现这一点吗?或javascript?
回答by Stickers
You can try CSS3 object-fit
, and see browser support tables.
您可以尝试 CSS3 object-fit
,并查看浏览器支持表。
CSS3
object-fit
/object-position
Method of specifying how an object (image or video) should fit inside its box. object-fit options include "contain" (fit according to aspect ratio), "fill" (stretches object to fill) and "cover" (overflows box but maintains ratio), where object-position allows the object to be repositioned like background-image does.
CSS3
object-fit
/object-position
指定对象(图像或视频)应如何放入其框内的方法。对象适合选项包括“包含”(根据纵横比适合)、“填充”(拉伸对象以填充)和“覆盖”(溢出框但保持比例),其中对象位置允许对象像背景一样重新定位-图像。
.container {
width: 200px; /*any size*/
height: 200px; /*any size*/
}
.object-fit-cover {
width: 100%;
height: 100%;
object-fit: cover; /*magic*/
}
<div class="container">
<img class="object-fit-cover" src="https://i.stack.imgur.com/UJ3pb.jpg">
</div>
Related Info:
相关信息:
回答by Sandeep K Nair
You can achieve this using css flex properties. Please see the code below
您可以使用 css flex 属性来实现这一点。请看下面的代码
.img-container {
width: 150px;
height: 150px;
border: 2px solid red;
justify-content: center;
display: flex;
flex-direction: row;
overflow: hidden;
}
.img-container .img-to-fit {
flex: 1;
height: 100%;
}
<div class="img-container">
<img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />
</div>