Opening
The top or bottom margin of a block element is sometimes combined into a margin, which is called the merge of the margin, which is collapsing margins.
A common CSS style bug
HTML&CSS:
<! DOCTYPE html><html> <style type="Text/css"> HTML,Body{ width: %; height: %; padding: 0; margin: 0; } #main { width: px; height: px; background: yellow; } #sub {color : #fff ; width : px ; padding : 0 ; margin : 0 ; margin-top : 20 px ; background : black ; </style><body> <div id="main"> <div id="Sub">This is sub block</div> </div></body></html>
Effect:
In the parent div wrapped in the style of the child div,css obviously want to let the child div and the parent container has a 20px margin-top, but unfortunately, the parent div and Sub-div overlap the top margin, and inexplicably with the body has a 20px top margin (body is a white background area).
This bug is common and often overlooked, but it reveals a very important concept, that is 外边距合并(Collapsing margins)
, to completely solve the problem (of course, you can fix the change in Chrome, but do you know the real reason?) ), or the official code of the Web, I intercepted a translation from MDN for ease of reading:
Margin merging occurs in the following three basic scenarios:
1.毗邻元素Adjacent siblings
The margins of adjacent elements are merged (except when the back element clears the float).
2.毗邻元素Adjacent siblings
If there is no border between the margin-top of the block element and its first child element, padding, inline content, or clearance delimited, or the margin-bottom of the block element There is no padding between the last child element, inline content, height, min-height, or max-height, and the margin is merged.
3.空块元素
If there is no border between the block element margin-top and margin-bottom, padding, inline content, height, and min-height are separated, then its upper and lower margins are merged.
You can see that the above bug belongs to Case 2, that is, as long as the main div set padding can be resolved (or border, depending on the situation).
Blog synchronization
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Collapsing margins (margin merge)