和
)清除浮动,并为其定义CSS代码clear:both。
代码实例:
.demo{
width: 500px;
margin: 50px auto;
background-color: #CCCCCC;
}
.left{
width: 100px;
height: 100px;
float: left;
background-color: #21B4BB;
}
.right{
width: 100px;
height: 50px;
float: right;
background-color: #21B4BB;
}
.clear{
clear:both;
}
优点:简单,代码少,浏览器兼容性好。
缺点:需要添加大量无语义的html元素,代码不够优雅,后期不容易维护。
2.使用CSS的overflow属性
使用overflow清除浮动:只需在需要清除浮动的元素中定义CSS代码overflow:auto或overflow:hidden即可。
代码实例:
.demo{
width: 500px;
margin: 50px auto;
background-color: #CCCCCC;
overflow:hidden
}
.left{
width: 100px;
height: 100px;
float: left;
background-color: #21B4BB;
}
.right{
width: 100px;
height: 50px;
float: right;
background-color: #21B4BB;
}
优点:不存在结构和语义化问题,代码量极少
缺点:内容增多时候容易造成不会自动换行导致内容被隐藏掉,无法显示需要溢出的元素
3.使用CSS的:after伪元素
对父元素使用:after伪元素,设置display:table
display:table 使生成的元素以块级表格显示,占满剩余空间。
通过content: " "生成内容作为最后一个元素,至于content里面是什么都是可以的,CSS经典的是 content:".",有些版本可能content里面内容为空。
代码实例:
.demo{
width: 500px;
margin: 50px auto;
background-color: #CCCCCC;
*zoom: 1;
}
.demo:after {
content: " ";
display: table;
clear: both;
}
.left{
width: 100px;
height: 100px;
float: left;
background-color: #21B4BB;
}
.right{
width: 100px;
height: 50px;
float: right;
background-color: #21B4BB;
}
缺点:适合现代浏览器,不支持IE6/7,*zoom: 1就是为了兼容IE6/7
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h62478.shtml