Do floated elements create a separate stacking context like positioned ones do?

前端 未结 1 1582
礼貌的吻别
礼貌的吻别 2021-02-07 09:00

Recently I lit upon an interesting article about the CSS z-index property. I found it because I was seeking for an answer about why overflowed text from a preceding div was disp

相关标签:
1条回答
  • 2021-02-07 09:39

    CSS2.1 specifies the painting order of elements as follows:

    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).

    Floats do not establish stacking contexts on their own. They will only do so if they are positioned and have a z-index that is not auto (not counting any of the numerous other ways an element may do so). Otherwise, they participate in the same stacking context as other elements, including inlines, with the following caveat (from the same link above):

    Within each stacking context, positioned elements with stack level 0 (in layer 6), non-positioned floats (layer 4), inline blocks (layer 5), and inline tables (layer 5), are painted as if those elements themselves generated new stacking contexts, except that their positioned descendants and any would-be child stacking contexts take part in the current stacking context.

    Since all elements in your fiddle are participating in the same stacking context, and your floating element is not positioned (#4), the inline contents of the overflowing div (#5) are painted above the floating element and its descendant elements, even though the floating element appears later in source order.

    The background of the overflowing div (#1) is painted below that of the float, however, because the background of the float is considered part of the float itself in accordance with the second quote above. You can see this by giving the float a negative margin:

    #floated {
      background-color: pink;
      width: 300px;
      float: left;
      margin-top: -50px;
    }
    
    0 讨论(0)
提交回复
热议问题