在<img>上方放置CSS背景图片

16
如何在HTML的<img>上重复使用1px x 1px的CSS背景图像?

http://jsfiddle.net/hjv74tdw/1/

我发现CSS在其他包含元素上显示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;
}
<div class="test">
    <img src="http://lorempixel.com/400/400">
</div>

3个回答

41

你可以使用伪元素。在这个例子中,: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;
}
<div class="test">
    <img src="http://lorempixel.com/200/200">
</div>

顺便提一下,你的例子之所以无法正常工作是因为父元素有一个背景图像,但由于子元素在父元素内创建了堆叠上下文,所以不可能让父元素的背景图像出现在子元素img的上方(除非你完全隐藏img元素)。这就是为什么z-index没有按预期工作的原因。

此外,img元素是绝对定位的。这样做会将其从正常流中移除,并且由于它是唯一的子元素,父元素因此也会崩溃并且没有任何尺寸。因此,背景图像不会显示出来。要解决这个问题,你需要为父元素设置明确的尺寸(height/width),或者可以取消子img元素的绝对定位。


1
这是我为解决方案所做的事情。基本上,我使用“IMG”作为占位符,以便我的背景图像在浏览器调整大小时保持正确的比例。
.image-overlay {
  background-image: url("insert image here");
  display: inline-block;
  position: relative;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
.image-overlay img {
  opacity: 0;
}

HTML
<div class="category-overlay">
    <img src="/images/placeholder.jpg" alt="">
</div>

1

另一种方法是将content设置为空,并设置背景,例如:

img {
    background: url(...) center center no-repeat;
    background-size: cover;
    content: '';
    display: block;
    width: 800px;
    height: 100px;
}

这是一个演示: http://jsfiddle.net/infous/effmea8x/ 在这个演示中,第一张图片的宽高不成比例,第二张图片是背景图片。第一张图片缩放得很糟糕,而第二张图片则正常。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接