更新时间: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>
以上几种方式都可以清除浮动,具体使用哪种方式取决于实际情况和需求。
毕业16个工作日,平均薪资13180元,就业率100%,广州黑马AI智能应用开发(Java)学科20250529班
2026-03-06毕业32个工作日,平均薪资11147元,就业率95%,广州黑马AI智能应用开发(Java)学科20250326班
2026-03-05黑马程序员2025全国就业数据发布:全学科平均就业率92.07%,AI开发类就业平均薪资达11869.67元。
2026-03-05黑马全国校区齐开班!场面太太太壮观了!
2026-03-03AI智能应用开发课程紧贴企业刚需,全程高效学习,直达中高级软件开发水平
2026-02-28风口正劲!黑马程序员又一AI智能应用开发班毕业当天100%就业!
2026-02-27