与图象元素的背景图象z索引问题

时间:2014-05-31 20:46:35

标签: 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;
}

2 个答案:

答案 0 :(得分:1)

您不能在元素内容之上拥有给定元素的背景....您需要对标记进行一些调整。

我分叉了你的笔:http://codepen.io/anon/pen/ipmDv

这是您的新HTML:

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

你的新CSS:

 #sidebar{
  width: 344px;
  float: left;
  height: 500px;
  margin-top: 45px;
  padding: 8px;
  position: relative;
  z-index: 1000;
}

.overlay{
  width: 116px;
  height: 116px;
  position: absolute;
  z-index:1000;
  background: url("http://i.imgur.com/BQc7nYP.png") no-repeat top right !important;
  top:0px;
  right:25px;
}

答案 1 :(得分:1)

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

纯CSS解决方案

但是,您可以使用位于:before元素顶部的pseudo-element:afterimg)(我已将其抵消所有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