为什么 position absolute 呈现在 position static 之上?

Why is position absolute rendered above position static?

我有一个简单的绝对 div 和另一个正常的 div 在后面。为什么绝对 div 呈现在另一个之上?

我知道我可以用 z-index 修复它 - 但原因是什么?

JSBIN: http://jsbin.com/yadoxiwuho/1

<style>
    .with-absolute {
      position:absolute;
      top:0px;
      bottom:0px;
      background-color:red
    }
    .other {
      background-color:yellow;
    }
  </style>
   </head>
<body>
  <div class="with-absolute">Hello</div>
  <div class="other">Why is this not on top? It comes last</div>
</body>

absolute The element is positioned relative to its first positioned (not static) ancestor element

Reference.

In the absolute positioning model, a box is explicitly offset with respect to its containing block. It is removed from the normal flow entirely (it has no impact on later siblings). An absolutely positioned box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants. However, the contents of an absolutely positioned element do not flow around any other boxes. They may obscure the contents of another box (or be obscured themselves), depending on the stack levels of the overlapping boxes.

Reference.

一般情况下,绝对元素的 z-index 默认值为 0,位于静态位置之上。如果你想把它移到后面,将 z-index 设置为 -1。

绝对值:

这意味着你可以把它放在任何地方,它不会影响或被流程中的任何其他元素影响。

与静态值和相对值不同,绝对定位元素从正常流中移除。

示例代码如下:

#box_1 { 
    position: absolute;
    top: 0;
    left: 0;
    width: 200px;
    height: 200px;
    background: #ee3e64;
}
#box_2 { 
    position: absolute;
    top: 0;
    right: 0;
    width: 200px;
    height: 200px;
    background: #44accf;
}

DEMO 来自作者 Noah Stokes 的 文档。

很明显,Noah Stokes DOCUMENT 关于 css 定位

所有静态元素都有默认的 z-index(自动),即零。

我唯一的逻辑解释是,当你将 position: relative|absolute|fixed 添加到一个元素时,你将它放在文档流之外,因此变成了 1 的 z-index。

元素的绘制顺序由CSS 2.1 spec, E.2 Painting order

决定

静态定位元素在第 4 步到第 7 步绘制。z-index 为 auto0 的绝对定位元素在第 8 步绘制,因此始终位于顶部。