css中clear:both属性的作用是清除浮动,设置了浮动就会破坏文档流结构,影响后边的布局,此时在设置清除浮动便可解决这一问题,可以认为,设置了clear:both的当前元素会把前边元素中设有浮动属性的元素,当做没设浮动一样来看待,以此来消除其对自己的影响
对比设置和不设置clear:both的结果来说明
<style>.test-title{background-color: orange;}.test-content{background-color: #ddd;height:100px;/* clear:both; */}.left{float: left;width: 200px;background-color: pink;}.right{float: left;background-color: aquamarine;}</style>
</head>
<body style="margin: 10px;"><div class="test-title">头部信息</div><div class="test-container"> <div class="left">左侧菜单</div><div class="right">右侧内容</div><div class="test-content" >we are one we are one we are one </div></div>
</body>
为什么会出现下边的情况呢,因为左侧菜单和右侧菜单设置了float:left,此时他们属于浮动流占据了一定位置,test-content的内容属于文档流所以会紧挨着test-container上边框
但当我们将test-content设置clear:both后,它就会消除前边浮动给他带来的影响,也就是无视left,right样式中设置的float:left属性,把left,right看做普通文档流,因test-content是块级元素会独占一行,所以就会变成如下情况,或者设置伪元素
.test-content::before,.test-content::after{
content:'';display:block;clear:both;
}