更新时间:2023-03-08 来源:黑马程序员 浏览量:
在前端开发中,浮动是经常用到的一种样式技巧,但同时也会带来一些问题,如高度塌陷(clearfix),不规则盒模型等。下面介绍几种清除浮动的方式,并提供详细的代码演示。
父级div手动定义height值,但如果子元素高度超出父元素,则会出现内容溢出的情况。
<div style="background-color: #ccc; height: 200px;"> <div style="float: left; width: 100px; height: 100px; background-color: red;"></div> <div style="float: right; width: 100px; height: 150px; background-color: blue;"></div> </div>
在浮动元素下方添加一个空div元素,利用clear:both清除浮动。但这种方式会增加无意义的标签。
<div style="background-color: #ccc;"> <div style="float: left; width: 100px; height: 100px; background-color: red;"></div> <div style="float: right; width: 100px; height: 150px; background-color: blue;"></div> <div style="clear: both;"></div> </div>
父级div添加overflow:auto样式,可以自动清除子元素的浮动,但需要注意滚动条的出现。
<div style="background-color: #ccc; overflow: auto;"> <div style="float: left; width: 100px; height: 100px; background-color: red;"></div> <div style="float: right; width: 100px; height: 150px; background-color: blue;"></div> </div>
在父级div中使用伪元素::after,利用clear:both清除浮动,但需要注意添加content属性,否则在某些浏览器中可能不起作用。
<div style="background-color: #ccc; position: relative;"> <div style="float: left; width: 100px; height: 100px; background-color: red;"></div> <div style="float: right; width: 100px; height: 150px; background-color: blue;"></div> <div style="clear: both;"></div> <div style="position: absolute; bottom: 0; left: 0; right: 0; height: 0; content: '';"></div> </div>
以上几种方式都可以清除浮动,具体使用哪种方式取决于实际情况和需求。
【AI设计】北京143期毕业仅36天,全员拿下高薪offer!黑马AI设计连续6期100%高薪就业
2025-09-19【跨境电商运营】深圳跨境电商运营毕业22个工作日,就业率91%+,最高薪资达13500元
2025-09-19【AI运维】郑州运维1期就业班,毕业14个工作日,班级93%同学已拿到Offer, 一线均薪资 1W+
2025-09-19【AI鸿蒙开发】上海校区AI鸿蒙开发4期5期,距离毕业21天,就业率91%,平均薪资14046元
2025-09-19【AI大模型开发-Python】毕业33个工作日,就业率已达到94.55%,班均薪资20763元
2025-09-19【AI智能应用开发-Java】毕业5个工作日就业率98.18%,最高薪资 17.5k*13薪,全班平均薪资9244元
2025-09-19