1、空标记法
在浮动元素之后添加空标记,并对该标记应用 ”clear:both“ 样式,即可清除浮动的产生的影响。
<style>
.one,.two,.three{
float: left;
width: 100px;
height: 100px;
margin: 10px;
background: red;
}
.box{
border: 1px solid #ccc;
background: blue;
}
.four{
clear: both; /* 清除左右两侧浮动影响,按原来块级元素显示 */
}
</style>
<body>
<div class="box">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
</div>
</body>
2、after伪对象
实现原理类似于第一种方法,区别是前者是在结构中插入一个空标记,而后者利用其为伪类::after在元素内部增加一个类似于空标记的效果。
<style>
.one,.two,.three{
float: left;
width: 100px;
height: 100px;
margin: 10px;
background: red;
}
.box{
border: 1px solid #ccc;
background: blue;
}
.box::after{
display: block;
clear: both;
content: "";
visibility: hidden;
height: 0;
}
</style>
<body>
<div class="box">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
</body>
3、overflow属性
为什么overflow能清楚浮动?overflow:hidden 触发了 BFC。
<style>
.one,.two,.three{
float: left;
width: 100px;
height: 100px;
margin: 10px;
background: red;
}
.box{
border: 1px solid #ccc;
background: blue;
overflow: hidden;
}
</style>
<div class="box">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>