html - 无法解释的 CSS float 和位置堆叠 :relative

标签 html css css-float css-position z-index

如果我有一个 float 的 <div id='1' style='float:right;'>controls and links</div>其次是 <div id='2' style='position:relative;'>lorem ipsum text here...</div> ,

#2 位于
#1 之上,阻止了任何鼠标交互。 (如果
#2 有纯色背景,它会完全隐藏
#1,但仍然“包裹”在
#1 周围。)为什么会这样?

即使我设置 z-index 也是如此两者的值,试图强制 float

#1 到顶部。

可以考虑四种情况。我把它们都放进了 this JSFiddle . (JSFiddle 还使用不透明度来说明堆叠。)

  1. float
    #1 没有 z-index 或位置;下面的
    #2 也没有 z-index 或位置。 结果:
    #1 堆叠在
    #2 之上,鼠标交互正常。
  2. float
    #1 没有 z-index 或位置;
    #2 也没有 z-index 但有 position:relative . 结果:
    #2 堆叠在
    #1 之上。无法进行鼠标交互。
  3. float
    #1 有 z-index:1000但没有位置;以下<div> #2 有 z-index:0position:relative . 结果:
    #2 仍然堆叠在
    #1 之上。无法进行鼠标交互。
  4. float
    #1 有 z-index:1000position:relative ;以下
    #2 有 z-index:0position:relative . 结果:
    #1 堆叠在
    #2 之上,鼠标交互正常。

我见过一些类似的 SO 问题,但没有任何问题可以准确解决这个问题。我还阅读了许多 CSS float 和定位文章,但似乎都没有解决这种情况。

最佳答案

在处理堆叠顺序时,我建议仔细阅读以下列表 section 9.9 of CSS2 :

Within each stacking context, the following layers are painted in back-to-front order:

  1. the background and borders of the element forming the stacking context.
  2. the child stacking contexts with negative stack levels (most negative first).
  3. the in-flow, non-inline-level, non-positioned descendants.
  4. the non-positioned floats.
  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  7. the child stacking contexts with positive stack levels (least positive first).

首先,您需要记住两件事:

  1. z-index 对非定位元素没有影响。这包括花车。这就是为什么在你的 float 上设置 z-index,而不定位它,不会改变任何东西。
  2. 来 self 对 a very similar question 的回答:“ float 不会自行建立堆叠上下文。只有当它们被定位并且具有非自动的 z-index(不计算 any of the numerous other ways an element may do so )时,它们才会这样做。”

这两点涵盖了为什么在场景 2 和场景 3 中 float 永远不会出现在其定位兄弟的前面:定位兄弟的堆栈级别为 0 (#6),这确保它被绘制在 float 前面 (#4) .

在场景 1 中,未定位的兄弟属于 #3,这就是为什么它被绘制在 float (#4)后面的原因。

在场景 4 中, float 变得完全无关紧要。您现在在同一个堆栈上下文中有两个定位元素,一个具有比另一个更大的堆栈级别(并且,正如 elsewhere 所暗示的那样,大了一个完全不必要的数量),因此具有更高的堆栈级别被绘制在具有更小堆栈级别的那个之上。

关于html - 无法解释的 CSS float 和位置堆叠 :relative,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43214089/