我想要一个图像来填充其容器宽度的100%,并且我希望它具有设置的max-heigth属性,所有这些都保持纵横比但允许丢失图像的任何部分.
img { max-height:200px; width:100%; }
我知道使用background-size属性可以做类似的事情,但我想将其设为内联< img>标签.
我怎么能用CSS实现这个目标?还是javascript?
解决方法
您可以尝试使用CSS3
object-fit
,并查看浏览器支持
tables.
@H_301_12@
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.
.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>
相关信息:
> Exploring object-fit ★ Mozilla Hacks
> Polyfill for CSS object-fit property