Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange margin issue with a display: inline-block child

Tags:

html

css

Heres the fiddle

When I set #two to inline-block it subtracts the 16 px of top/bottom margin from the <p> and adds it to the divs content box height so it becomes 52px instead of 20px .. why is this the case?

like image 614
Adrift Avatar asked Jan 14 '23 01:01

Adrift


1 Answers

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.

like image 66
jamesplease Avatar answered Jan 19 '23 10:01

jamesplease