如何在HTML上重复这个1px x 1px CSS背景图像<img>?
http://jsfiddle.net/hjv74tdw/1/
我在其他包含的元素之上遇到了CSS show div背景图像,但它似乎需要一个额外的div.理想情况下,我希望我根本不必使用div,但根据CSS背景图像而不是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;
}Run Code Online (Sandbox Code Playgroud)
<div class="test">
<img src="http://lorempixel.com/400/400">
</div>Run Code Online (Sandbox Code Playgroud)
Jos*_*ier 32
您可以使用伪元素.在此示例中,:after伪元素相对于父元素绝对定位.它采用整个父元素的维度,父元素的大小由子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;
}Run Code Online (Sandbox Code Playgroud)
<div class="test">
<img src="http://lorempixel.com/200/200">
</div>Run Code Online (Sandbox Code Playgroud)
作为旁注,您的示例由于几个原因而无法正常工作.父元素具有背景图像,但由于子元素在父元素中建立堆叠上下文 ,因此父元素的背景图像不可能出现在子元素上方img(除非您完全隐藏img元素).这就是z-indexs没有按预期工作的原因.
此外,img元素绝对定位.在这样做时,它从正常流中移除,并且由于它是唯一的子元素,因此父元素自身折叠并且它没有任何尺寸.因此,背景图像不会显示出来.要解决此问题,您可能必须在父元素(height/ width)上设置显式尺寸,或者可以删除子img元素上的绝对定位.