使用CSS将图像放在div后面

时间:2014-10-22 15:33:09

标签: html css

我有以下标记(小提琴示例:http://jsfiddle.net/9gvj11o5/8/

<div class="header">           
  <div class="image">
    <img src="http://placehold.it/2200x800" alt=""/>
  </div>    
  <div class="menu">This is the menu</div>    
  <div class="tools">These are the tools</div>        
</div>    
<div class="content">content</div>    

以下CSS:

.header {
  position: relative;
}

.image {
  position: absolute;
}

img {
  width: 100%;
  height: auto;
  outline: 0;
}

我需要图像响应并且100%宽度与顶部对齐。

但是我还需要菜单和工具来覆盖图像并保持正常流动。

内容应该在图片之后,所以在标题之后。

图像将是&#34;背景&#34;头部div。 (我不能使用背景图片)

我正在使用位置,但菜单和工具在我使用它的那一刻就消失了。

我错过了什么?我在某处需要另一个包装器吗?

2 个答案:

答案 0 :(得分:1)

您可以使用z-index来定义元素的图层顺序。数字越小,越接近&#34;底部&#34;堆栈。所以我们给img一个非常小的数字,菜单和工具非常大。

.header {
    position: relative;
}

.image {
    position: absolute;
    z-index: 1; /* here you can use -1 as Paulie_D points out in the comments */
}

img {
    width: 100%;
    height: auto;
    outline: 0;
    z-index: 2; /* here you can use -1 as Paulie_D points out in the comments */
}

.menu {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 888; /* You can remove this declaration entirely if you set -1 above */
}

.tools {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 888; /* You can remove this declaration entirely if you set -1 above */
}

答案 1 :(得分:1)

我会包装2个div .menu&amp; .tools所以您只需将z-index应用于包装div而不是每个孩子。使.menu&amp; .tools(包裹)在.image前面。

然后将position:absolute更改为position:relative.image,以使.content低于header

下面你可以看到非常轻量级的片段。

.header {
    position: relative;
}
.image {
    position: relative;
    z-index:1
}
#menu-all {
    position:absolute;
    top:0;
    z-index:2
}
img {
    width: 100%;
    height: auto;
    outline: 0;
}
<div class="header">
    <div class="image">
        <img src="http://placehold.it/2200x800" alt="" />
    </div>
    <div id="menu-all">
        <div class="menu">This is the menu</div>
        <div class="tools">These are the tools</div>
    </div>
</div>
<div class="content">content</div>