CSS 6.2补充 清除浮动的方法
一.为什么要清除浮动
.div1{background:#800080;border:1px solid red;}
.div2{background:#800080;border:1px solid red;height:100px;margin-top:10px}
.div11{width: 80px;height: 80px;background: red;float: left;}
.div12{width: 80px;height: 80px;background: red;float: left;}
.div13{width: 80px;height: 80px;background: red;float: left;}
<div class="div1">
<div class="div11"></div>
<div class="div12"></div>
<div class="div13"></div>
</div>
<div class="div2"></div>
结果:
由于div1没有撑开,造成:
1.div1后面的元素div2位置错误
2.div1的(1):背景不能显示 (2):边框不能撑开 (3):margin设置值不能正确显示
所以要清除浮动,所谓的清除浮动,就是将未撑开的块撑开。
二.清除浮动的几种方法:
1.在父元素里添加新的元素,应用 clear:both;
.div1{background:#800080;border:1px solid red;}
.div2{background:#800080;border:1px solid red;height:100px;margin-top:10px}
.div11{width: 80px;height: 80px;background: red;float: left;}
.div12{width: 80px;height: 80px;background: red;float: left;}
.div13{width: 80px;height: 80px;background: red;float: left;}
.clear{clear:both;}
<div class="div1">
<div class="div11"></div>
<div class="div12"></div>
<div class="div13"></div>
<div class="clear"></div>
</div>
<div class="div2"></div>
注:别处都一样,只是添加了红色部分
编程思想:
在未撑开的块里,添加一个空的块且这个空块clear:both。
2.为父元素添加属性overflow:hidden
.div1{background:#800080;border:1px solid red;overflow:hidden; zoom: 1; }
.div2{background:#800080;border:1px solid red;height:100px;margin-top:10px}
.div11{width: 80px;height: 80px;background: red;float: left;}
.div12{width: 80px;height: 80px;background: red;float: left;}
.div13{width: 80px;height: 80px;background: red;float: left;}
<div class="div1">
<div class="div11"></div>
<div class="div12"></div>
<div class="div13"></div>
</div>
<div class="div2"></div>
注:别处都一样,只是添加了红色部分。zoom:1;处理兼容性问题
3.为父元素添加伪元素:after
.div1{background:#800080;border:1px solid red; }
.div2{background:#800080;border:1px solid red;height:100px;margin-top:10px}
.div11{width: 80px;height: 80px;background: red;float: left;}
.div12{width: 80px;height: 80px;background: red;float: left;}
.div13{width: 80px;height: 80px;background: red;float: left;}
.div1 {zoom:1;} /*==for IE6/7 Maxthon2==*/
.div1:after {clear:both;content:””;display:block;height: 0;visibility:hidden;} /*==for FF/chrome/opera/IE8==*/
<div class="div1">
<div class="div11"></div>
<div class="div12"></div>
<div class="div13"></div>
</div>
<div class="div2"></div>
注1:别处都一样,只是添加了红色部分。zoom:1;处理兼容性问题。
注2:.div1:after中间不能有空格。
编程思想:
在div1里面,div1元素的结尾插入元素。也就是说在div13后面。
同样是在未撑开的块里,添加一个空的块且这个空块clear:both。
看下面test:
.clearfloat{zoom:1;}
.div1:after{clear:both;content:"after";display:block;background: blue;}
结果:
4.给父元素定高
5.父元素浮动
6.父元素处于绝对定位