在一个bfc中,垂直方向上相邻的块级盒子产生外边距塌陷,本文要说一个特殊的外边距塌陷情况,即当垂直方向上,两个块级盒子之间有个浮动元素相隔时,这个时候会产生什么样的效果呢?
.outer{ overflow: auto; width: 300px; height: 500px; border: 2px solid #6666FF; } .box{ width: 100px; height: 100px; font-family: "simhei"; } .top{ margin-bottom: 20px; background: #CC6600; } .float{ /*float: left;*/浮动部分被注释掉了 } .bottom{ margin-top: 10px; background: #33FF66; }<div class="outer"> <div class="top box">top</div> <div class="float"></div> <div class="bottom box">bottom</div> </div>
效果图:
Paste_Image.png
然后我把中间的div设置一下:
.float{ float: left; margin-bottom: 10px; background: #9900CC; width: 50px; height: 50px; }<div class="float">float</div>
效果如图:
立即学习“前端免费学习笔记(深入)”;
Paste_Image.png
可知:浮动元素不会影响后续块级盒子与前面块级盒子的外边距塌陷。但当我们利用bottom清除浮动时
.bottom{ margin-top: 10px; background: #33FF66; clear: both; }效果图:
Paste_Image.png
可知:使用清除浮动属性的元素,它的外边距塌陷规则变成如下规则:闭合浮动的盒子的border-top始终和浮动元素的margin-bottom底部重合。而在闭合浮动的盒子的margin-top上方,直到top盒子的margin-bottom底部这段距离,就是我们所说的clearance。验证:
.float{ float: left; margin-top: 10px; margin-bottom: 10px; background: #9900CC; width: 50px; height: 50px; }
Paste_Image.png
2.调整浮动元素的高度和margin
.float{ float: left; margin-top: 5px; margin-bottom: 5px; background: #9900CC; width: 50px; height: 5px; } .bottom{ margin-top: 20px; background: #33FF66; clear: both; }效果图:
Paste_Image.png
此时bottom元素的margin-top和top元素的margin-bottom重合了5px。此时clearance的值是-5px。通过上面两个验证,我们就可以知道有浮动元素时,闭合浮动元素的clearance是怎么计算的了。一个基本原则就是闭合浮动的元素的border-top与浮动元素的margin-bottom重合。
另外,从上面的验证2中我们也可以总结出,浮动元素与border,padding这样的屏蔽外边距塌陷的属性不同,浮动元素是脱离文档流的,所以当浮动元素没有大到足以分开BFC中的相邻盒子时,相邻盒子的垂直margin还是会重叠的。
参考资料:
http://www.w3cplus.com/css/understanding-bfc-and-margin-collapse.html
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号