为什么位置:相对;将背景元素放在前面?

时间:2013-07-31 09:32:13

标签: css

.main-column h2 {
    padding-top: 110px;
    padding-bottom: 110px;
    background: url('someimagehere.png') no-repeat center top;
    margin: 0 auto;
    position: relative; /*so that the image stays on top.*/
}

.text-column {
    width: 215px;
    background-color: yellow;
    margin-top: -120px; /*so that it enters inside the h2*/
    padding-top: 120px;
    margin-left: auto;
    margin-right: auto;
}

<div class="main-column">
 <h2>Hello tittle 1</h2>
  <div class="text-column">
   <p>I'm on column 1 and I like it</p>
   <p>I'm on column 1 as well</p>
  </div>
</div>

这样可行,但我不明白。

为什么给h2提供“position:relative”,将背景图像放在那里可见,在另一个元素黄色背景颜色的顶部?

同样,此代码有效。我只是在寻求帮助来理解这种行为。

请咨询

3 个答案:

答案 0 :(得分:2)

使用position:relative或position:absolute或position:fixed允许您还使用z-index值来确定堆叠顺序。

如果在h2上设置z-index:-1,它应该将其推回到其他元素后面。或者,您可以在另一个元素上设置position:relative,并在其上设置更高的z-index。

答案 1 :(得分:1)

  

没有z-index的堆叠

     

当没有元素具有z-index时,元素按此顺序堆叠   (从下到上):

     
      
  • 根元素的背景和边框
  •   
  • 正常流程中的后代阻塞,按外观顺序(以HTML格式)
  •   
  • 后代按照外观(以HTML格式)
  • 定位元素   

在MDN阅读the full articleand the other six articles eplaining Z-Index)。

通过启用WebGL,您还可以在3D中观看页面进行调试:使用 FireFox ,按 CTRL SHIFT < kbd> K ,然后单击右侧的立方体图标以3D形式查看页面。然后单击鼠标并拖动以旋转并检查z轴上发生的情况。

答案 2 :(得分:0)

当你将一个元素放到position:relative;时,它会覆盖其他元素,如果你希望它保留在后台,请在你的H2上使用z-index: -1;

相关问题