发布时间:2025-12-09 14:10:52 浏览次数:6
之前一直不明白clear的意义何在,一直以为clear就是去掉元素本身都浮动属性(即使元素的float设置为none),如果这样理解就显得clear非常多余。最近再次接触到clear才弄明白clear的本来意义。
下面直接看实例:
1. 没有清除浮动
<html> <head> <style type="text/css"> .p1{ float: left; width: 100px; background-color: #0f0; word-break: break-all; } .p2{ float: left; width: 100px; background-color: #f00; word-break: break-all; /*clear: left;*/ } .p3{ width: 300px; background-color: #00f; word-break: break-all; } </style> </head> <body> <p class = "p1"> aaaaaaaaaaaaaaaaa </p> <p class = "p2"> ddddddddddddddddd </p> <p class = "p3"> 1234567890qwertyuioplkjhgfdsazxcvbnm bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb </p> </body></html>运行后的结果是:
我们可以看到p2跟在p1的后面
2. 清除浮动
.p2{ float: left; width: 100px; background-color: #f00; word-break: break-all; clear: left; }运行结果:
我们看到p2在p1下面了,但是p2的float并没有被清除(不是float:none,而是float:left),也就是说p2还是向left浮动了,为什么这样说呢,现在我把p2的float设置为none:
.p2{ float: none; width: 100px; background-color: #f00; word-break: break-all; clear: left; }运行效果:
p2因为没有浮动,所以和p3同处在标准流里面,因此可以证明上一步的p2是向left浮动的。此时我们可以明白clear的作用了,就是不让元素本身跟在之前的浮动元素后面,而是在之前元素的下一行进行left/right浮动。
<html> <head> <style type="text/css"> .p1{ width: 100px; background-color: #0f0; height: 100px; } .p2{ width: 100px; background-color: #f00; height: 150px; } .p3{ float: left; width: 300px; background-color: #00f; height: 300px; overflow: hidden; } .p{ float: left; } </style> </head> <body> <p > <p class = "p1"> 姓名 </p> <p class = "p2"> 班级 </p> </p> <p class = "p3"> 简介 </p> </body></html>利用clear的做法:
<html> <head> <style type="text/css"> .p1{ float: left; width: 100px; background-color: #0f0; height: 100px; } .p2{ float: left; width: 100px; background-color: #f00; clear: left; height: 150px; } .p3{ width: 300px; background-color: #00f; height: 300px; overflow: hidden; } </style> </head> <body> <p class = "p1"> 姓名 </p> <p class = "p2"> 班级 </p> <p class = "p3"> 简介 </p> </body></html>现在班级、姓名、简介平起平坐了,不用在班级和姓名外再裹一层了……
参考:
准确理解CSS clear:left/right的含义及实际用途