总结六种清除CSS浮动的方法
1.父元素定义height
<span style="font-family:Microsoft YaHei;"><style>
.wrapper {
width:600px;
height:200px;/* 解决代码 */
background:red;
}
.left {
float:left;
width:30%;
height:100px;
background:yellow;
}
.right {
float:right;
width:30%;
height:100px;
background:green;
}
</style>
<div class="wrapper">
<div class="left">
鬼眼邪神的博客
</div>
<div class="right">
鬼眼邪神的博客
</div>
</div></span>
原理:手动定义父元素的高度,解决其不能自动获取高度的问题。
缺点:必须给出精确地高度,无法自适应。
2.利用空标签清浮动
<span style="font-family:Microsoft YaHei;"><style>
.wrapper {
width:600px;
background:red;
}
.left {
float:left;
width:30%;
height:100px;
background:yellow;
}
.right {
float:right;
width:30%;
height:100px;
background:green;
}
/* 解决代码 */
.clear {
clear:both;
}
</style>
<div class="wrapper">
<div class="left">
鬼眼邪神的博客
</div>
<div class="right">
鬼眼邪神的博客
</div>
<div class="clear">
</div>
</div></span>
原理:在父元素的关标签之前加入一空标签,用clear:both来清浮动。
缺点:如果需要清浮动的地方很多,则需要加入很多空标签,很麻烦。
3.父元素设置overflow:hidden
<span style="font-family:Microsoft YaHei;"><style>
.wrapper {
width:600px;
background:red;
overflow:hidden;
}
.left {
float:left;
width:30%;
height:100px;
background:yellow;
}
.right {
float:right;
width:30%;
height:100px;
background:green;
}
</style>
<div class="wrapper">
<div class="left">
鬼眼邪神的博客
</div>
<div class="right">
鬼眼邪神的博客
</div>
</div></span>
原理:必须定义width或zoom:1,同时不能定义height,使用overflow:hidden具有清除内部浮动的效果。
缺点:当与position配合使用时,有可能会造成内容被隐藏。
4.父元素定义伪类:after
<span style="font-family:Microsoft YaHei;"><style>
.wrapper {
width:600px;
background:red;
}
/* 解决代码 */
.wrapper:after {
display:block;
clear:both;
overflow:hidden;
content:'';
height:0;
visibility:hidden;
}
.left {
float:left;
width:30%;
height:100px;
background:yellow;
}
.right {
float:right;
width:30%;
height:100px;
background:green;
}
</style>
<div class="wrapper">
<div class="left">
鬼眼邪神的博客,地址
</div>
<div class="right">
鬼眼邪神的博客,地址
</div>
</div></span>
原理:使用:after伪类在浮动块后面加上一个非display:none的不可见块状内容来,并给它设置clear:both来清理浮动。
5.父元素定义overflow:auto
<span style="font-family:Microsoft YaHei;"><style>
.wrapper {
width:600px;
background:red;
overflow:auto;/* 解决代码 */
}
.left {
float:left;
width:30%;
height:100px;
background:yellow;
}
.right {
float:right;
width:30%;
height:100px;
background:green;
}
</style>
<div class="wrapper">
<div class="left">
鬼眼邪神的博客
</div>
<div class="right">
鬼眼邪神的博客
</div>
</div></span>
原理:必须定义width或zoom:1,同时不能定义height,使用overflow:auto时,浏览器会自动检查浮动区域的高度
缺点:内容超出父元素宽高时会出现滚动条。
6.父元素设置float属性
<span style="font-family:Microsoft YaHei;"><style>
.wrapper {
width:600px;
background:red;
float:left;/* 解决代码 */
}
.left {
float:left;
width:30%;
height:100px;
background:yellow;
}
.right {
float:right;
width:30%;
height:100px;
background:green;
}
</style>
<div class="wrapper">
<div class="left">
鬼眼邪神的博客
</div>
<div class="right">
鬼眼邪神的博客
</div>
</div></span>
您可能感兴趣的文章:
CSS浮动属性Float入门教程
css下clear both、left、right值的含义
CSS Float 浮动方式
css 两种清除浮动经典实例代码
CSS规范 闭合浮动元素介绍
css清除浮动几种做法
css中清除浮动方法介绍
CSS浮动与清除浮动(overflow)例子
DIV CSS布局中无法显示背景颜色是怎么回事
css利用clearfix方法清除浮动详解