html - 图像元素的背景图像 z-index 问题

标签 html css z-index

我想将背景图像叠加到图像上。密码是here . 如何将背景图像放在 img 元素上?

我的 html 是;

<div id="sidebar">
        <div class="editor-select">
            <img src="http://i.imgur.com/mh3noQH.jpg" alt="img"/>
        </div>
    </div>

我的CSS是;

  #sidebar{
  width: 344px;
  background: url("http://i.imgur.com/BQc7nYP.png") no-repeat top right !important;
  float: left;
  height: 500px;
  margin-top: 45px;
  padding: 8px;
  position: relative;
  z-index: 1000;
}

.editor-select{
  width: 350px;
  height: 360px;
  position: relative;
}

.editor-select>img{
      width: 320px;
    height: 160px;
   z-index : -1;
}

最佳答案

你不能。您的 img 元素包含在 #sidebar 元素中,这有效地使 img 元素位于 #sidebar 元素。您不能将父元素置于其子元素之上。

纯 CSS 解决方案

但是,您可以使用 pseudo-element (:before:after),位于 img 元素的顶部(我在所有 4 边都偏移了 6px 以允许图像正确重叠):

.editor-select:after {
      content: '';
      position: absolute;
      top: -6px;
      left: -6px;
      height: 172px;
      width: 332px;
      background: url("http://i.imgur.com/BQc7nYP.png") no-repeat top right
}

CodePen Demo .

Demo

关于html - 图像元素的背景图像 z-index 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23974418/

相关文章:

javascript - 使用 for 循环创建 div 元素

html - 如何防止滚动条插入元素?

javascript - 使用 bootstrap 4 在 html 中的另一个图像上叠加图像

Javascript 切换 : Hide div on click of anywhere

CSS z-index 问题

css - 不满足模式要求时文本字段显示错误(HTML5)

javascript - .offsetWidth、.width、.width() 等并不总是在自动调整大小的元素上正确返回

jquery - 在 Canvas 上方绘制选区时的偏移

html - Chrome/Safari 和 Firefox 中的 z-index 问题(嵌套元素)

html - 如何将我的移动菜单置于内容之上?