为什么需要清除浮动
前面有一篇博客中有提到关于”浮动塌陷”的描述http://blog.csdn.net/github_38861674/article/details/77427309
由于包含元素里面的元素都设置为浮动,导致包含元素的高度塌陷为0,如下图所示:
这种塌陷进而会产生如下后果:
- 包含元素的背景和边框不能生效
margin 和padding值不能生效,特别是上下的margin和padding值
如何清除浮动:
一、clear属性:
clear属性有五种可能的值:
right:不允许右边出现浮动元素
left: 不允许左边出现浮动元素
both:不允许两边出现浮动元素
none:默认值,允许两边出现浮动元素
inherit:继承
下面来看看代码演示:
heml结构为:
<div class="container">
<div class="float1">float-1</div>
<div class="float2">float-2</div>
</div>
1、不设置float时:父元素高度为两个子块状元素的高度和
.container{
width: 200px;
border: 2px solid #ddd;
}
.container .float1{
width: 80px;
height: 80px;
background-color: yellow;
}
.container .float2{
width: 80px;
height: 80px;
background-color: yellow;
}
2、子元素都设置浮动时:父元素高度为0,发生了”浮动塌陷”
.container{
width: 200px;
border: 2px solid #ddd;
}
.container .float1{
width: 80px;
height: 80px;
float: left;
background-color: yellow;
}
.container .float2{
width: 80px;
height: 80px;
float: left;
background-color: yellow;
}
3、当给float1元素清除有浮动时:显示效果没有差别
.container{
width: 200px;
border: 2px solid #ddd;
}
.container .float1{
width: 80px;
height: 80px;
float: left;
clear: right;
background-color: yellow;
}
.container .float2{
width: 80px;
height: 80px;
float: left;
background-color: yellow;
}
4、当给子元素float2添加clear:left 时,float2元素下移,但是父元素仍然
5、在子元素后面添加一个空的div,然后这个div设置clear:both;或者clear:left;
html结构
<div class="container">
<div class="float1">float-1</div>
<div class="float2">float-2</div>
<div class="clear"></div>
</div>
css样式
.container{
width: 200px;
border: 2px solid #ddd;
clear: both;
}
.container .float1{
width: 80px;
height: 80px;
float: left;
background-color: yellow;
}
.container .float2{
width: 80px;
height: 80px;
float: left;
background-color: yellow;
}
.clear{
clear: left;
}
效果图:
二、overflow属性
只给父元素设置overflow:hidden;或者auto,就可以了;
.container{
width: 200px;
border: 2px solid #ddd;
overflow: hidden;
}
.container .float1{
width: 80px;
height: 80px;
float: left;
background-color: yellow;
}
.container .float2{
width: 80px;
height: 80px;
float: left;
background-color: yellow;
}
.clear{
clear: left;
}
after 选择器
给父元素设置:
:after伪元素
.container{
width: 200px;
border: 2px solid #ddd;
}
.container:after{
content: '';//给父元素的内容后添加空的字符串
visibility: hidden;
display: block;
height: 0;//高度为0,不会挤压其他元素
clear: both; //清除为元素两边的浮动
}
.container .float1{
width: 80px;
height: 80px;
float: left;
background-color: yellow;
}
.container .float2{
width: 80px;
height: 80px;
float: left;
background-color: yellow;
}