CSS背景图像位于顶部<img>



如何在HTML <img>顶部重复此1px x 1px CSS背景图像

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

我在其他包含的元素上看到了CSS显示div背景图像,但它似乎需要一个额外的div。理想情况下,我希望我根本不必使用div,但根据HTML img上的CSS背景图像,这是不可能的,至少对于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伪元素绝对位于相对于父元素的位置。它采用整个父元素的维度,父元素的大小由子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上的绝对定位。

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

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

下面是一个演示:http://jsfiddle.net/infous/effmea8x/

在这个演示中,第一张图像是标准的,但宽度和高度不成比例,第二张是背景图像。第一个缩放不好,第二个还可以。

以下是我为解决方案所做的操作。从本质上讲,我使用"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>

相关内容

最新更新