Why is setting the top-margin of this child element pushing its parent container down with it?

后端 未结 4 783
别跟我提以往
别跟我提以往 2020-12-17 00:22

I have two divs:

S

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 00:46

    This is due to margin collapsing:

    Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

    This is resulting in the parent element reverse-inheriting the child element top margin.

    You can prevent this by adding   before the child element

    Demo Fiddle

    ....or applying any of the below to the parent:

    1. float: left / right
    2. position: absolute
    3. display: inline-block

    Adding display:inline-block; to the parent likely being the preference if it is set to have a width to 100%

    Demo Fiddle

提交回复
热议问题