为什么要清除浮动
清除浮动是为了解决,因为子元素浮动,引起的父元素内部高度为 0 的问题。
示例
当父元素不设置高度时:
- 子元素不浮动,父元素会被子元素撑开:
- 子元素添加浮动后,父元素高度为 0 ,变成一条线;
<div class='father'>
<div class='big'>big</div>
<div class='small'>small</div>
</div>
.father{
border:1px solid red;
}
.big{
background-color:orange;
height:200px;
width:200px;
/* float:left; */
}
.small{
background-color:blue;
height:100px;
width:100px;
/* float:left; */
}
清除浮动
- 父元素上添加
clearfix
<div class='father clearfix'>
.clearfix::after{
content:"";
display:block;
clear:both;
}
clearfix{
zoom:1; /* IE 兼容*/
}
- 父元素加上
overflow:hidden;,用 BFC 清除浮动。