Collapsed margin in CSS

前端 未结 2 1691
礼貌的吻别
礼貌的吻别 2021-01-25 02:49

MDN explains collapsed margin here.

These are the basic 3 rules it explains:

Adjacent siblings

The margins of adjace

2条回答
  •  孤城傲影
    2021-01-25 03:48

    The margins of #empty collapse through, resulting in a 20px collapsed-through margin. This collapsed-through margin collapses with the 10px bottom margin of the first paragraph, and the 10px top margin of the last paragraph. This results in a 20px gap between the first and last paragraphs, since the collapsed-through margin is larger than either of their margins and therefore swallows them both.

    Your observation is correct: #empty, when its collapsed through, is rendered with its top margin. From the spec:

    • [...] The position of the element's top border edge is the same as it would have been if the element had a non-zero bottom border.

    Note that the positions of elements that have been collapsed through have no effect on the positions of the other elements with whose margins they are being collapsed; the top border edge position is only required for laying out descendants of these elements.

    The position that "would have been if the element had a non-zero bottom border" is the position of the element if the element's margins did not collapse through, since having a non-zero bottom border blocks the margins from collapsing through.

提交回复
热议问题