消除浮动的方法
为了清除由于元素浮动后脱离文档流导致的父级元素高度塌陷问题,可以在CSS中添加一个伪类:
.clearfix::after{
content:"";
display:block;
zoom:1;
height:0px;
clear:both;
}
然后再在塌陷的父级元素中添加一个clearfix类,如:
.father{
width:100%;
border:2px #bfa solid; //添加边框使得效果更明显
}
.son{
height:100px;
width:100px;
border:1px red solid; //添加边框使得效果更明显
}
<div class="father">
<div class="son"></div>
</div>
以上代码效果如下:
在开启浮动后导致高度塌陷,代码及效果如下:
.father{
width:100%;
border:2px #bfa solid; //添加边框使得效果更明显
}
.son{
height:100px;
width:100px;
border:1px red solid; //添加边框使得效果更明显
float:left; //开启浮动
}
<div class="father">
<div class="son"></div>
</div>
加上clearfix清除浮动类后,代码及效果如下:
.father{
width:100%;
border:2px #bfa solid; //添加边框使得效果更明显
}
.son{
height:100px;
width:100px;
border:1px red solid; //添加边框使得效果更明显
float:left; //开启浮动
}
.clearfix::after{
content:"";
display:block;
zoom:1;
height:0px;
clear:both;
}
<div class="father clearfix">
<div class="son"></div>
</div>
可以看到父级元素又回到了被内容撑起的高度
clearfix为一般公认下的清除浮动类名,如果有别的想法可以改动类名,如:
.father{
width:100%;
border:2px #bfa solid; //添加边框使得效果更明显
}
.son{
height:100px;
width:100px;
border:1px red solid; //添加边框使得效果更明显
float:left; //开启浮动
}
.abaaba::after{
content:"";
display:block;
zoom:1;
height:0px;
clear:both;
}
<div class="father abaaba">
<div class="son"></div>
</div>
清除浮动一般用于想保留浮动带来的元素效果并且使父级元素不会产生宽高变化之时。