如何在 <img> 标签中使用 CSS 背景附件?

9 css image background-image

您将如何使用 CSS 样式background-attachment并将其应用到<img>标签?

<img src="ok.jpg">
Run Code Online (Sandbox Code Playgroud)

CSS:

img {
  background-attachment: fixed;
} 
Run Code Online (Sandbox Code Playgroud)

小智 20

添加此内容是为了防止其他人在这里寻求复制在 HTML 中background-attachment: fixed;使用img标签时的行为。

您无法按要求在标签上使用背景属性,但您可以通过在图像及其容器上<img>使用来复制其行为。position: fixedclip-path

例子:

div {
  position: relative;
  height: 200px;
  margin: 50px 10px;
  clip-path: inset(0);
}

img {
  object-fit: cover;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

body {
  min-height: 400px;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <img src="https://picsum.photos/id/237/200/300">
</div>
Run Code Online (Sandbox Code Playgroud)


Cro*_*Toa 2

你不能那样做。首先background-attachment是CSS“函数”,你只能为background-image. 您还可以通过 img 获得类似的视图position:fixed

img {
     position: fixed;
} 
Run Code Online (Sandbox Code Playgroud)

尝试JsFiddle