CSS:使图片位于 div 的顶部

CSS: Make an image come to the top of a div

我的HTML:

<div id="why">
    <div class="gallery clearfix">
        <img src="images/why-bg.png" class="background-why">
        <div class="gallery-inner">
            ...
        </div>
        <div class="gallery-inner">
            ...
        </div>
        <div class="gallery-inner">
            ...
        </div>
    </div>
</div>

我的 CSS:

#why{
  height: 100%;
}
#why .gallery{
  height: 100%;
  width: 100%;
  position: relative;
}
#why .background-why{
  position: absolute;
  top: 0;
  left: 0;
  float: left;
}

我希望 .background-why 超过 .gallery。但它与我的代码一起位于 .gallery 之下。我认为这张图片将帮助您了解我的期望

Z-index 就是您的答案。将顶部元素的 z-index 设置为高于背景元素

#why{
  height: 100%;
}
#why .gallery{
  height: 100%;
  width: 100%;
  position: relative;
  z-index:1;
}
#why .background-why{
  position: absolute;
  top: 0;
  left: 0;
  float: left;
  z-index:2;
}

使用 z-index:

#why .background-why{
  position: absolute;
  top: 0;
  left: 0;
  float: left;
  z-index:1
}

为您的 .background-why class 使用 z-index 属性。

您的 css 应如下所示:

#why{
  height: 100%;
}
#why .gallery{
  height: 100%;
  width: 100%;
  position: relative;
}
#why .background-why{
  position: absolute;
  top: 0;
  left: 0;
  float: left;
  z-index: 1;
}

根据您的需要:

1) 如果您希望 .background-why 永久位于 .gallery-inner 之上(整个区域都是 .gallery-inner)- jsfiddle.net/bw6ecbuy/1/

2) 如果你想让 .background-why 在悬停时超过 .gallery-inner 则:jsfiddle.net/a8yszLsf/2/

如果我理解有误,请发表评论。