一、清除浮动的原因
在实际应用中,父盒子一般是不方便给高度的,但子盒子常常需要设置浮动进行排版。我们知道,浮动的盒子是不占有位置的,若父盒子又没有设置高度,那么会使父盒子的高度变为0,影响到后面的标准流盒子。
二、清除浮动的本质和语法
1.本质:就是清除浮动元素造成的影响,清除浮动之后,父盒子就会根据浮动的子盒子自动检测高度,子盒子占有多高,父盒子就有多高。父盒子有了高度之后,就不会影响后面的标准流盒子了。
2.语法:选择器{clear:属性值;}
属性值有三个:
left:不允许左侧有浮动元素(清除左侧浮动的影响)
right:不允许右侧有浮动元素(清除右侧浮动的影响)
both:同时清除左右两侧浮动的影响(常用)
三、清除浮动的方法
1.额外标签法(隔墙法)
在浮动元素末尾添加一个空的标签
缺点:添加了无意义的标签,结构化较差
<html>
<style>
.father{
border: 1px solid #000;
}
.son1{
float: left;
width: 200px;
height: 200px;
background-color: skyblue;
}
.son2{
float: left;
width: 200px;
height: 200px;
background-color: rgb(45, 225, 69);
}
/* 添加样式 */
.clear{
clear:both
}
</style>
</head>
<body>
<div class="father">
<div class="son1">儿子1</div>
<div class="son2">儿子2</div>
<!-- 添加空盒子,必须为块元素 -->
<div class="clear"></div>
</div>
</body>
</html>
2.父级添加overflow
可以给父级添加overflow属性,属性值设为hidden(常用)、auto或scroll
缺点:无法显示溢出的部分
<style>
.father{
/* 添加overflow属性 */
overflow: hidden;
width: 800px;
border: 1px solid #000;
margin: 0 auto;
}
.son1{
float: left;
width: 200px;
height: 200px;
background-color: skyblue;
}
.son2{
float: left;
width: 200px;
height: 200px;
background-color: rgb(45, 225, 69);
}
</style>
<body>
<div class="father">
<div class="son1">儿子1</div>
<div class="son2">儿子2</div>
</div>
</body>
3.清除浮动——:after伪元素法
<style>
/* 添加:after */
.clearfix:after{
content:"";
display:block;
height:0;
clear:both;
visibility: hidden;
}
/* 为了兼容IE6、7浏览器 */
.clearfix{
*zoom:1;
}
.father{
width: 800px;
border: 1px solid #000;
margin: 0 auto;
}
.son1{
float: left;
width: 200px;
height: 200px;
background-color: skyblue;
}
.son2{
float: left;
width: 200px;
height: 200px;
background-color: rgb(45, 225, 69);
}
</style>
<body>
<!-- 给父盒子添加clearfix类名 -->
<div class="father clearfix">
<div class="son1">儿子1</div>
<div class="son2">儿子2</div>
</div>
</body>
4.清除浮动——双伪元素法
<style>
.clearfix:before,
.clearfix:after{
content:"";
display:table;
}
.clearfix:after{
clear:both;
}
/* 为了兼容IE6、7浏览器 */
.clearfix{
*zoom:1;
}
.father{
width: 800px;
border: 1px solid #000;
margin: 0 auto;
}
.son1{
float: left;
width: 200px;
height: 200px;
background-color: skyblue;
}
.son2{
float: left;
width: 200px;
height: 200px;
background-color: rgb(45, 225, 69);
}
</style>
<body>
<!-- 给父盒子添加clearfix类名 -->
<div class="father clearfix">
<div class="son1">儿子1</div>
<div class="son2">儿子2</div>
</div>
</body>