如何在 HTML 顶部重复这个 1px x 1px CSS 背景图像 <img>
?
http://jsfiddle.net/hjv74tdw/1/
我遇到了 CSS show div background image on top of other contained elements ,但是它似乎需要一个额外的 div。理想情况下,我希望我根本不必使用 div,但根据 CSS Background-image over HTML img这实际上是不可能的,至少对于 100% 宽度响应的场景而言是不可能的。
.test {
background: url(http://placehold.it/1/1) repeat;
position: relative;
z-index: 100;
width: 200px;
}
.test img {
width: 100%;
display: block;
position: absolute;
z-index: 50;
}
<div class="test">
<img src="http://lorempixel.com/400/400">
</div>
最佳答案
您可以使用伪元素。在此示例中,:after
伪元素相对于父元素绝对定位 relative。它采用整个父元素的尺寸,父元素的大小由子 img
元素的大小决定。
.test {
display: inline-block;
position: relative;
}
.test:after {
content: '';
position: absolute;
top: 0; right: 0;
bottom: 0; left: 0;
background: url(http://placehold.it/20x20/1) repeat;
}
<div class="test">
<img src="http://lorempixel.com/200/200">
</div>
附带说明一下,您的示例由于多种原因无法正常工作。父元素有一个背景图像,但是由于子元素建立了一个 stacking context 在 父元素中,父元素的背景图像不可能出现在子 img
元素的上方(除非您要完全隐藏 img
元素)。这就是 z-index
没有按预期工作的原因。
此外,img
元素是绝对定位的。这样做时,它会从正常流中移除,并且由于它是唯一的子元素,因此父元素会自行折叠并且没有任何尺寸。因此,背景图像不会显示。要解决此问题,您要么必须在父元素上设置显式尺寸(height
/width
),要么可以删除子元素上的绝对定位 img
元素。
关于html - <img> 顶部的 CSS 背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28710659/