我想要CSS图像覆盖的行为,它填充容器元素但不改变图像的比例;任何不适合容器元素视口(viewport)的内容都会延伸到容器之外并被隐藏。
但是,它在 CSS 中的工作方式(从我到目前为止的使用方式来看)是将其放置在图像中心周围。
我想说的是“将封面 anchor 设置为图像的 x = 150 和 y = 375”类型的东西。想知道如何做到这一点。这样,我可以在图像上选择一个点并将其作为封面的中心点。
最佳答案
您需要使用background-position
作为背景图像,或使用object-position
作为具有objec-fit
的图像
您需要通过将坐标除以图像尺寸并乘以 100% 来计算正确的值
background-position: calc(131 / 200 * 100%) calc(66 / 200 * 100%);
/* ^^^ ^^^ ^^ ^^^
||| ||| || |||
||| ||| || image height
||| ||| y coordinate
||| image width
x coordinate
*/
点击按钮,您将触发动画,显示焦点位于这些图像中的鸟上
document.addEventListener('click', e => {
if (e.target.nodeName.toLowerCase() == 'button') {
document.getElementById(e.target.dataset.id).classList.toggle('animate')
}
})
.container {
display: inline-block;
background-image: url(https://picsum.photos/id/990/200/200);
background-size: cover;
background-position: calc(131 / 200 * 100%) calc(66 / 200 * 100%);
transition: all 1s ease-in-out;
}
img {
-o-object-fit: cover;
object-fit: cover;
-o-object-position: calc(131 / 200 * 100%) calc(66 / 200 * 100%);
object-position: calc(131 / 200 * 100%) calc(66 / 200 * 100%);
transition: all 1s ease-in-out;
}
.animate[data-property=width] {
width: 5px !important;
}
.animate[data-property=height] {
height: 5px !important;
}
<span id="container-1" data-property="width" class="container" style="width:200px; height:100px"></span>
<span id="container-2" data-property="height" class="container" style="width:100px; height:200px"></span>
<img id="image-1" data-property="width" src="https://picsum.photos/id/990/200/200" alt="" style="width:200px; height:100px">
<img id="image-2" data-property="height" src="https://picsum.photos/id/990/200/200" alt="" style="width:100px; height:200px">
<br>
<button data-id="container-1">Animate</button>
<button data-id="container-2">Animate</button>
<button data-id="image-1">Animate</button>
<button data-id="image-2">Animate</button>
关于html - 如何为 CSS img 封面设置 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56424201/