【问题标题】:CSS background image on top of <img><img> 顶部的 CSS 背景图像
【发布时间】:2015-04-26 22:52:49
【问题描述】:

如何在 HTML &lt;img&gt; 之上重复这个 1px x 1px CSS 背景图像?

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>

【问题讨论】:

    标签: html css


    【解决方案1】:

    您可以使用伪元素。在此示例中,: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>

    附带说明,您的示例无法正常工作有几个原因。父元素有背景图片,但由于子元素在父元素建立了stacking context,因此父元素的背景图片不可能出现在子元素的上方 img 元素(除非您要完全隐藏 img 元素)。这就是z-indexs 没有按预期工作的原因。

    此外,img 元素是绝对定位的。这样做时,它会从正常流程中移除,并且由于它是唯一的子元素,因此父元素会自行折叠并且没有任何尺寸。因此,背景图像不显示。要解决此问题,您必须在父元素 (height/width) 上设置显式尺寸,或者您可以删除子 img 元素上的绝对定位。

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

        【解决方案3】:

        这是我为解决方案所做的。本质上,我使用“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>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-06
          • 1970-01-01
          • 1970-01-01
          • 2010-10-04
          相关资源
          最近更新 更多