html stack order

蓝咒 提交于 2019-12-05 21:51:32

Because the two elements are each in-flow, non-positioned, block-level elements in the same stacking context.

Two in-flow, non-positioned blocks aren't strictly "above" or "below" each other -- their contents and backgrounds stack separately.

Adding position: relative will make an element positioned (with z-index: auto) and place it above non-positioned elements in the same stacking context: it will be rendered at step 8 in the painting algorithm below.


If you read the CSS2 spec's Elaborate description of Stacking Contexts closely, you will see that this is correct behavior.

In-flow, non-positioned, block-level elements within the same stacking context first have all their backgrounds rendered, then all their contents. Their backgrounds are above positioned elements with a negative z-index and below everything else.

The relevant steps in the painting algorithm:

  1. ...
  2. ...
  3. ...
  4. For all its in-flow, non-positioned, block-level descendants in tree order: If the element is a block, list-item, or other block equivalent:
    1. background color of element.
    2. background image of element.
    3. border of element.
  5. ...
  6. ...
  7. ... for all its in-flow, non-positioned, block-level descendants in tree order:
    1. ...
    2. ... for each line box of that element:
      1. For each box that is a child of that element, in that line box, in tree order:
        1. ...
        2. ...
        3. ...
        4. For inline elements:
          1. For all the element's in-flow, non-positioned, inline-level children that are in this line box, and all runs of text inside the element that is on this line box, in tree order:
            1. If this is a run of text, then:
              1. ...
              2. ...
              3. the text.
              4. ...
  8. ...
  9. ...
  10. ...

Floated and positioned elements are always "atomic" -- their backgrounds and contents will be rendered together in a single step (either step 3, 5, 8 or 9). But in-flow, non-positioned block elements within the same stacking context have all their backgrounds rendered (in step 4), then have all their contents rendered (in step 7).

In this case, for in-flow, non-positioned sibling elements H1 and P (H1 before P in the tree), step 4 renders the H1 background and then the P background, then step 7 renders the H1 content and then the P content.

The default stacking order for HTML elements is that elements later in the code are "above" earlier elements.

Add this to the CSS:

position: relative;
z-index: 2;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!