Understanding margin-collpasing

前端 未结 1 1954
一整个雨季
一整个雨季 2021-01-27 03:45

I have successfully gotten the margin of the h2 element to be contained within its container - the section element. This way it doesn\'t collapse with the margin of the p elemen

1条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 04:04

    Since elements with overflow set to anything other than visible can't have their margins collapsed, why does the effect I've successfully achieved only work when the container (section) element is set to auto? Why does it not work when the h2 element is set to auto?

    This is not true. overflow will disable the margin collapsing between the element and its inflow first (or last) child and not with its siblling. Overflow create a Block Formatting Context and this will isolate all the elements inside from any outside interaction.

    h2 {
      margin:10px 0;
      overflow:auto; /* this will do nothing */
    }
    
    .box {
      margin:10px 0;
      outline:1px solid red;
    }

    some text

    some text

    some text

    some text

    In the above example, all the margin will collapse but not the ones between the second section and its childs h2.

    When we take away the margin of the p element, and don't have section set to auto, h2 loses its upper-margin. Why does this happen? It doesn't seem to be in contact with another margin which would make it collapse.

    The h2 will collpase with the margin of section which is 0 and the resulting margin will be moved to section:

    p {
      margin: 0;
    } 
    
    section {
      /*overflow: auto;*/
      background:red;
    }

    I am a p element

    I am an h2 element

    Even if an element has a margin equal to 0 it can collapse with other margin:

    0 讨论(0)
提交回复
热议问题