先来看设置浮动后,未清除的效果:
我们给父元素设置了背景颜色,但是由于浮动,此时没有背景颜色
<!DOCTYPE html>
<html>
<head>
<title>清除浮动</title>
<style type="text/css">
.father{
border: 1px solid red;
background: #fc9;
}
.div1{
width: 80px;
height: 80px;
background: red;
float: left;
}
.div2{
width: 80px;
height: 80px;
background: blue;
float: left;
}
</style>
</head>
<body>
<div class="father">
<div class="div1">1</div>
<div class="div2">2</div>
</div>
</body>
</html>
接下来清除浮动:
方法一:
是给所有浮动标签后面加一个空标签元素,定义style为 clear:both
弊端;增加了无意义的标签,不利于后期维护
具体看代码
<!DOCTYPE html>
<html>
<head>
<title>清除浮动</title>
<style type="text/css">
.father{
border: 1px solid red;
background: #fc9;
}
.div1{
width: 80px;
height: 80px;
background: red;
float: left;
}
.div2{
width: 80px;
height: 80px;
background: blue;
float: left;
}
/*方法一*/
.clear{
clear:both;
height: 0;
line-height: 0;
font-size: 0
}
</style>
</head>
<body>
<div class="father">
<div class="div1">1</div>
<div class="div2">2</div>
</div>
</body>
</html>
方法二:使用over-flow
具体是给浮动的父元素添加一个css属性 over-flow:auto;zoom:1或者over-flow:hidden;zoom:1 ,其中zoom:1是用来兼容IE6的
具体看代码
<!DOCTYPE html>
<html>
<head>
<title>清除浮动</title>
<style type="text/css">
.outer{
border: 1px solid red;
background: #fc9;
color: #fff;
}
.div1{
width: 80px;
height: 80px;
background: red;
float: left;
}
.div2{
width: 80px;
height: 80px;
background: blue;
float: left;
}
/*方法二*/
.over-flow{
overflow: hidden;
zoom: 1;
/*zoom: 1; 是在处理兼容性问题*/
}
.outer {
zoom:1;
/*==for IE6/7 Maxthon2==*/
}
</style>
</head>
<body>
<div class="outer over-flow">
<div class="div1">1</div>
<div class="div2">2</div>
<!-- <div class="clear"></div> -->
</div>
</body>
</html>
清除浮动后的效果图:
方法三:使用:after伪对象 ,此方法只适用于非IE浏览器,
关键点:
1 content属性是必须有的,可以为空,也可以是'.'
2 height设置为0;
具体看代码;
<!DOCTYPE html>
<html>
<head>
<title>清除浮动</title>
<style type="text/css">
.outer{
border: 1px solid red;
background: #fc9;
color: #fff;
}
.div1{
width: 80px;
height: 80px;
background: red;
float: left;
}
.div2{
width: 80px;
height: 80px;
background: blue;
float: left;
}
/*方法三*/
.outer:after {
clear:both;
content:'.';
display:block;
width: 0;
height: 0;
visibility:hidden;
/*==for FF/chrome/opera/IE8==*/
}
.outer {
zoom:1;
/*==for IE6/7 Maxthon2==*/
}
</style>
</head>
<body>
<div class="outer over-flow">
<div class="div1">1</div>
<div class="div2">2</div>
<!-- <div class="clear"></div> -->
</div>
</body>
</html>
效果图和上面一样: