使用HTML <img>标记代替CSS background-image属性作为背景图像?

Get*_*k99 3 html css image

我需要将html <img>标记用作的背景图像<div>。然后,我将在其上放置一个<p>内容。我已经尝试过了,但是似乎无法正确显示它们。我使用了相对位置,负值的边距。

任何建议或指出我正确的方向将不胜感激。

<div>

  <img src="http://www.shiaupload.ir/images/77810787432153420049.png" />

  <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book
  </p>

</div>
Run Code Online (Sandbox Code Playgroud)

Fle*_*euv 5

为了使用于背景图像的功能几乎完美复制,我们必须考虑img包含的功能:

  • 它没有任何指针事件。
  • 它在下方至少渲染了一层div

结果是像这样的jsfiddle

div {
    display: inline-block;
    overflow: hidden;
    position: relative;
    width: 100%;
}

img {
    pointer-events: none;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: -1;
}
Run Code Online (Sandbox Code Playgroud)

您可以根据需要修改宽度和高度。

  • 你应该使用 100% 的 `min-width` 和 `min-height`。如果您使用“宽度”和“高度”,图像将在调整大小时拉伸 (3认同)
  • img也可以使用object-fit:cover;复制具有background-size:cover;的背景图像。 (2认同)

eya*_*ler 5

将来,这可能可以通过新的 css element() 函数实现:

background-image: element(img_element_id)

https://developer.mozilla.org/en-US/docs/Web/CSS/element