我在阅读CSS2.2,但是我真的无法理解这句话的意思,以及它所适合的场景:
If the top and bottom margins of an element with clearance p. 157 are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.
StackOverflow上有个家伙也提了一样的问题,回答者的答案我也不理解。。。
借用采纳者的知乎链接,这句的意思是:
If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.(有间隙不折叠)
哪,什么才是有间隙呢?这里的间隙clearance在css2.2中有定义。来个例子,先有个直观的理解吧:
<html>
<head>
<style>
* {padding: 0; margin: 0;}
#b1 {
width: 300px;
height: 100px;
margin-bottom: 4em;
background-color: #0d8ba1;
}
#F {
float: left;
width: 100px;
height: 70px;
background-color: yellow;
}
#b2 {
/*clear: both;*/
width: 300px;
height: 100px;
background-color: red;
margin-top: 2em;
}
</style>
</head>
<body>
<p id="b1"></p>
<p id="F"></p>
<p id="b2"></p>
</body>
</html>
运行时,对比#b2有clear:both
与没clear:both
时,b1与b2margin的折叠情况。
设置clear:both之后,#b2为了避开浮动的F,往下移动,出现了clearance
也就是空隙,b1与b2不再折叠!
另外,stack overflow那个家伙的答案我没再细究。pass。
You can see it here: https://www.zhihu.com/question/24563593
This explanation is also quite clear:
http://www.raccoon-tech.com/css-margin-collapse
As long as you understand that the condition for clearance is that when the
clear
element is not cleared (normally), itsboarder top
is higher than theboarder bottom
of the float element. If the clear element is originally under the float element, clearance will not occur.So this rule in plain language is: for an element with clearance, when it
margin top
andmargin bottom
are adjacent (for example,height
is 0, there is nopadding
andborder
), these two The margin will be calculated together with the margin of the next adjacent element, but will not be calculated with themargin bottom
of the parent element (in this case, only these two margins will be calculated).Also note here that the clearance calculation is based on the boarder edge, so for the
margin top
andmargin bottom
collapse elements, you must finally note that they will also swallow up a height equivalent tomargin top
.