css - 关于margin折叠的一个问题。
问题描述
我在阅读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。
问题解答
回答1:可以看这里:https://www.zhihu.com/question/24563593
回答2:这个说明也挺清晰的:http://www.raccoon-tech.com/css-margin-collapse
回答3:只要理解 clearance 产生的条件是当 clear 的元素在没有被 clear 的时候(正常时),它的 boarder top 要比 float 元素的 boarder bottom 要高。如果 clear 的元素本来就在 float 元素下面,就不会产生 clearance。
If this hypothetical position of the element’s top border edge is not past the relevant floats, then clearance is introduced, and margins collapse according to the rules in 8.3.1.
所以这个规则大白话就是:对于一个带 clearance 的元素,当它 margin top 和 margin bottom 相邻时(比如 height 为 0 、没有 padding 和 border),这个两个 margin 会跟接下来相邻元素的 margin 一起计算 collapsing,但不会跟父元素的 margin bottom 计算(这情况下就是只算这两个 margin)。
这里还要注意 clearance 计算是以 boarder edge 做参考,所以对于 margin top 和 margin bottom collapse 的元素,最后要注意还会吞掉与 margin top 相当的高度。
Then the amount of clearance is set to the greater of:
The amount necessary to place the border edge of the block even with the bottom outer edge of the lowest float that is to be cleared.
The amount necessary to place the top border edge of the block at its hypothetical position.
相关文章:
1. python - 求一个在def中可以实现调用本def满足特定条件continue效果的方法(标题说不太清楚,请见题内描述)2. $fields = $values = [];这条代码一直定义不了,一直报错,老师的源码也是被报错的,执行不了,请问该怎么解决这个问题3. USE关键字4. javascript - mysql插入数据时怎样避免与库中的数据重复?5. MySQL 这句 创建表结构语句的错误在哪?6. 导入phpmyadmin的时候报错了7. MySQL能否给某个字段的值设置有效期?8. 求一个mySQL安装包9. mysql数据库做关联一般用id还是用户名10. MySQL 如何 SELECT 除去某一列的所有列?
