Strange margin issue with a display: inline-block child

前端 未结 4 1869
温柔的废话
温柔的废话 2020-12-19 17:19

Heres the fiddle

When I set #two to inline-block it subtracts the 16 px of top/bottom margin from the

and adds it to the divs c

4条回答
  •  旧时难觅i
    2020-12-19 17:32

    What you're seeing is one of the stranger cases of margin collapsing.

    If the parent and children are block elements and there's nothing (padding, a border, etc.) separating their vertical margins, then those margins will collapse. Collapsed margins are when two neighboring margins aren't added (as you might expect), but instead the larger of the two is displayed. In the parent-child case, the collapsed margin ends up outside the parent. You can read more details under the section Parent and first/last child in the above link.

    Setting the parent to inline-block, or float:left;ing it or a number of other things (refer to the link for a more complete list) will stop the margins from collapsing. This leads to the behavior we're used to: the child's margin will appear inside the parent, adding to its total height, and the parent's margin will also be displayed.

提交回复
热议问题