Negative margin remove background property of static siblings

后端 未结 2 1441
北海茫月
北海茫月 2021-01-13 01:21

I am using negative margin on bottom to pull the adjacent element to overlap current element. It is my intention to make it overlap. But I want the whole div to be overlappe

相关标签:
2条回答
  • 2021-01-13 01:51

    In your sample code, both elements share the same stacking context.

    That being the case, the rules which define how elements are layered are defined in the spec as follows: (bold is mine)

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

    So you can see that - within the same stacking context - inline-level elements (#5) are painted above non-inline-level elements (#3)

    So in your case - since both the <img> and the <div> share the same stacking context and the <img> element is an inline-level element - it is painted above the <div> - even though the <div> occurs later in the document tree order.

    Check out this codepen demo which illustrates this point further


    Extra reading:

    Elaborate description of Stacking Contexts

    Stacking without z-index (MDN)

    Z-Index And The CSS Stack: Which Element Displays First?

    0 讨论(0)
  • 2021-01-13 01:54

    Position: relative will solve your issue of overlapping

    <style>
        .div1 {
          background-color: black;
          position: relative;
        }
    
        img {
          margin-bottom:-20px;
        }
    
      </style>
    
    0 讨论(0)
提交回复
热议问题