各种清浮动方法总结
一:(1)clear清浮动
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{
float: left;
width:200px;
height: 200px;
background-color: red;
}
.box2{
float:left;
clear:left;
width:300px;
height:300px;
background-color: green;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
(2)在浮动元素后添加空标签,设置clear:both
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{
float: left;
width:200px;
height: 200px;
background-color: red;
}
.box2{
float:left;
width:300px;
height:300px;
background-color: green;
}
.clear{
clear: both;
display: block;
float: none;
font-size:0;
margin:0;
padding:0;
overflow: hidden;
visibility:hidden;
height:0;
width:0;
background: none;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="clear"></div>
<div class="box2"></div>
</body>
</html>
二:overflow清浮动
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{
float: left;
width:200px;
height:200px;
background: green;
}
.box2{
float:left;
width:200px;
height:200px;
background: navy;
}
.box3{
height: 200px;
width:400px;
background: olive;
}
.main{
overflow: hidden;
}
</style>
</head>
<body>
<div class="main">
<div class="box1"></div>
<div class="box2"></div>
</div>
<div class="box3"></div>
</body>
</html>
这里我们为box1,box2的父元素设置overflow:hidden,同样可以达到清浮动的效果。
三:为父级元素定义高度
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{
float: left;
width:200px;
height:200px;
background: green;
}
.box2{
float:left;
width:200px;
height:200px;
background: navy;
}
.box3{
height: 200px;
width:400px;
background: olive;
}
.main{
height:200px;
}
</style>
</head>
<body>
<div class="main">
<div class="box1"></div>
<div class="box2"></div>
</div>
<div class="box3"></div>
</body>
</html>
当我们使用浮动后,浮动元素的父级元素无法自动获取高度,这时手动为其设置高度后可解决问题。
四:after伪类清浮动
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box1{
float: left;
width:200px;
height:200px;
background: green;
}
.box2{
float:left;
width:200px;
height:200px;
background: navy;
}
.box3{
height: 200px;
width:400px;
background: olive;
}
.clear:after{
visibility:hidden;
display:block;
font-size:0;
content:".";
clear:both;
height:0;
}
.clear{
zoom:1;
}
</style>
</head>
<body>
<div class="main clear">
<div class="box1"></div>
<div class="box2"></div>
</div>
<div class="box3"></div>
</body>
</html>
说明:给容器添加clear类即可达到清除浮动的目的,因为清浮动需要在浮动元素后面,所以不用:before。首先用content属性插入了一个句点,默认情况下content属性插入的内容是行内元素,需要将其display:block,才能使clear:both生效,为了不让插入的内容影响原来的布局,需要height:0将其高度设为0。
优化后的清除浮动的样式:
.clear:after{
content:".";
display: block;
height:0;
clear:both;
}
.clear{
zoom:1;
}
先总结到这。。。