css - 在不使用 z-index 的情况下将一个 div 层叠在另一个之上时观察到的意外结果

标签 css css-float position z-index

我有两个 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 遮盖底部的边框。 (在这种情况下我无法删除边框)。

通常,我会通过设置 position: relative 来做到这一点和 z-index在两个 div 上,(确保 div#onez-index 高于 div#two),然后添加 margin-bottom: -1pxdiv#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; 
}

但我早些时候搞砸了,注意到如果我 float 顶部的 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 - 在不使用 z-index 的情况下将一个 div 层叠在另一个之上时观察到的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11713253/

相关文章:

html - 无法移动#element1,这是为什么?

html - CSS 可能会溢出的预滚动元素

javascript - Div 出现在其正常位置 "during the time they are displaying"下方并具有动画效果?

javascript - 这种CSS的目的是什么?

php - 使用 PHP 静态文件加载器加载 CSS 样式时出现问题

html - Clearfix 小组不在 UL 中工作

css - 如果 "all DIVs in different lines"t 只停留在一行中,如何获取 "DIVs can'"

html - 布局在 Localhost 上看起来不错,但在实时网站上出现问题?

javascript - Spring中css、js文件放在哪里?

android 跨度点击事件