为什么相对定位元素出现在浮动元素之上?

Why does a relative positioned element appear above a floated element?

我有两个元素:一个具有相对定位,定义了我的大部分 header,还有一个较小的元素,我想 "float" 在它上面。

<div id=floater style="float:right">
Floater!
</div>
<div id=header style="width: 100%; position: relative; background-color: lightgreen">
This is the header
</div>

this fiddle所示,浮动组件不可见。但是,如果您删除 position: relative,则浮动元素会立即弹出。 Futzing z-index 没有产生任何有趣的东西。

header 组件不是 "mine";它是通过 React-Bootstrap 继承的。我可以覆盖,但现在我主要想了解浮动和相对定位的相互作用。

定位元素时,它们可以与其他元素重叠。如果两个定位元素重叠而没有指定 z-index,则 HTML 代码中最后定位的元素将显示在顶部。

没有设置位置 属性 的元素将默认为 "position:static",这会忽略所有定位属性,例如 z-index。通过为 header 元素设置相对定位,您已将 z-index 定位 属性 引入该元素,使其位于没有 z-index [= 的浮动元素前面33=].

由于 z-index 将被静态浮动元素忽略,因此您必须为该元素指定一个位置 属性(绝对、相对或固定),以便它可以具有 z-index 作为嗯

对于您的示例 "position: relative;" 可以。在浮动元素上设置位置 属性 后,您需要向其添加一个高于 header 元素的 z-index 值。在这种情况下,z-index:1 会是一个更高的值,因为 z-index 设置为默认值。

示例:

<div id=floater style="float:right; position: relative; z-index: 1;">
   Floater!
</div>
<div id=header style="width: 100%; position: relative; background-color:   lightgreen">
  This is the header
</div>

这是painting order

的函数

第 4 步中绘制了流内、非定位、块级元素

浮动项目是在第 5 步绘制的。因此浮动元素是静态 div 的 "on top" 绘制的,您会看到它显示出来。

但是用'z-index: auto'或'z-index: 0'定位的后代是在第8步绘制的。所以将position:relative添加到div意味着它现在被绘制了"on top" 的浮动元素,将其隐藏。