清除浮动是CSS中常见的问题,下面就来总结下平时遇到的浮动问题。
<div style="background:yellow;border:1px solid red;width:320px;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
由上图可以看出,我们内部DIV都采取了浮动的方式实现了左右布局,然而,外部div,由于内部浮动的缘故没有展示出应有的结构,相应的如果后面还有其他元素的话,就会出现重叠的问题。所以这种情况下,我们需要使用清除浮动,来使外部DIV占有需要的空间。清除浮动的方式有很多种:
1 因为浮动后父级元素没有被内部元素撑起来,那么我们可以直接给父级元素一个合适的高度,这样就可以清除浮动了。
<div style="background:yellow;border:1px solid red;width:320px;/*清除浮动代码*/height:120px;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
添加高度以后,即使里面浮动,父级元素还是会占用相应的高度。这样就有一个缺点:如果高度不能确定时,我们就不能给父级元素添加合理的高度了。
2 在浮动的元素后添加没有浮动的空标签
<div style="background:yellow;border:1px solid red;width:320px;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
<div style="clear:both;"></div>
</div>
添加没有浮动的元素,且clear:both,同样也可以解决浮动的问题,但是问题来了,这样的话,如果含有浮动的元素过多,每一个都向后面添加一个空元素的话,势必早上结构冗余,降低性能。
3 给父级元素定义伪类:after和zoom
<style>
.father:after{
content:'';
clear:both;
height:0;
display:block;
visibility: hidden;
}
.father:after{
zoom:1;
}
</style>
<div class="father" style="background:yellow;border:1px solid red;width:320px;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
在这里:after伪类的作用相当于给浮动元素后天添加一个空元素,但是只需要几行CSS代码,比较节省空间,zoom的作用是用来兼容浏览器的。
4 给父元素定义overflow:hidden/auto;
当使用overflow时,父元素必须要定义width.
<div style="background:yellow;border:1px solid red;/*清除浮动代码*/width:320px;overflow:auto;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
<div style="background:yellow;border:1px solid red;/*清除浮动代码*/width:320px;overflow:hidden;">
<div style="background:greenyellow;width:100px;height:100px;float:left;"></div>
<div style="background:blue;width:100px;height:100px;float:left;"></div>
<div style="background:#999;width:100px;height:100px;float:left;;"></div>
</div>
使用overflow也会出现相应的问题,overflow:auto时,如果超出父级宽度就会出现滚动条,overflow:hidden时如果超出父级元素宽度会被隐藏。所以要掌握好父级元素的宽度才行。