我如何调整框内图像的大小和位置,使其覆盖整个框,类似于 background-size: cover
的工作方式。
<div class="box" style="width: 100px; height: 100px;">
<img src="pic.jpg" width="413" height="325">
</div>
我知道我必须将 overflow:hidden
添加到框中并且图像需要 position: absolute
。但是,让我获得正确的图像新尺寸和左侧 + 顶部位置的公式是什么?
最佳答案
它的值(value):现在可以单独使用 CSS 来完成...
新的 CSS 属性 object-fit ( Current browser support )
只需在 img
上设置 object-fit: cover;
您甚至不需要将 img
包装在 div
中!
img {
width: 100px;
height: 100px;
}
.object-fit {
display: block;
object-fit: cover;
}
.original {
width: auto;
height: auto;
display: block;
}
<img src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>Img 'squashed' - not good</p>
<img class="object-fit" src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>object-fit: cover -
The whole image is scaled down or expanded till it fills the box completely, the aspect ratio is maintained. This normally results in only part of the image being visible. </p>
<img class="original" src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>Original ing</p>
您可以在 webplatform article 中阅读有关此新属性的更多信息.
还有,这里是a fiddle来自上面的文章,它演示了 object-fit
属性的所有值。
关于javascript - 如何模拟背景大小 : cover on <img>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38243886/