html - 如何为 CSS img 封面设置 anchor

标签 html css flexbox

我想要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/

相关文章:

javascript - html 连接语法错误 : unexpected identifier

css - 具有受限父容器的 flexbox 布局中的多个滚动 div?

javascript - 我的左边位置由于某种原因不在右边

html - 如何构建我自己的嵌入式音频播放器//不是纯闪存

html - INPUT 自动填充剩余的容器宽度

javascript - 使音频进度条过渡更平滑

css - 如何在一个三 Angular 形的盒子里放东西?

css - Angular-material:限制 md-content 高度

html - 如何强制垂直 flexbox 中的(旋转)元素不重叠?

html - CSS - 居中对齐