【问题标题】:Serendipitous results observed whilst layering a div on-top of another, without using z-index在不使用 z-index 的情况下将 div 层叠在另一个 div 上时观察到的意外结果
【发布时间】:2012-07-29 21:50:00
【问题描述】:

我有两个 div,(100 像素 x 100 像素)一个堆叠在另一个顶部,底部 div 顶部有黑色边框:请参阅fiddle

<div id="top"></div>
<div id="bottom"></div>​

div { 
  width: 100px; 
  height: 100px; 
}

#top { 
  background: tomato; 
}

#bottom { 
  border-top: 1px solid black; background: gold; 
}

我想使用顶部 div 来隐藏底部的边框。 (在这种情况下我无法删除边框)。

通常,我会通过在两个 div 上设置 position: relativez-index 来做到这一点,(确保 div#onez-index 高于 div#two),然后将 margin-bottom: -1px 添加到 div#one,参见 fiddle - css 因此变为:

div { 
  width: 100px; 
  height: 100px; 
  position: relative; 
}

#top { 
  z-index: 9999; 
  margin-bottom: -1px; 
  background: tomato; 
}    

#bottom { 
  z-index: 1; 
  border-top: 1px solid black; 
  background: gold; 
}

但我之前搞砸了,并注意到如果我浮动顶部 div(同时保持负的底部边距),并清除底部的 div(以便它们保持垂直堆叠),那么我不需要使用position: relative 或 z-index 隐藏边框,只要我将负底部边距添加到顶部 div(而不是底部的负顶部边距) - 请参阅 fiddle

div { 
  width: 100px; 
  height: 100px; 
}

#top { 
  float: left; 
  margin-bottom: -1px; 
  background: tomato; 
}    

#bottom { 
  clear: both; 
  border-top: 1px solid black; 
  background: gold; 
}

这很好用,我更喜欢它,因为要编写的代码更少。那么这里发生了什么?这是一种有效的、跨浏览器的将一个东西叠加在另一个之上的方法,还是最好坚持第一种方法,我使用 z-index,就像我一直做的那样?

【问题讨论】:

    标签: css css-float position z-index


    【解决方案1】:

    这是一个跨浏览器问题。最好坚持我认为的第一种方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 2012-10-13
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多