CSS中清除浮动的方式

什么是浮动?

使元素脱离文档流(标准流),按照指定方式发生移动,遇到父级边界或者相邻的浮动元素就停下来的一种现象。

float:left|right|inherit|initial|none;

下面看一个例子:

<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
	<title>浮动</title>
	
	<style type="text/css"> 
		
		#box{
			width:400px;
			border:1px solid blue;
		}
		
		.float{
			width:100px;			
			height:100px;
		    float:left;
		}
		
		#box1{
			background-color:red;			
		}
		#box2{
			background-color:green;		  
		}
		
		#box3{
			background-color:yellow;
		}
	</style>
	
</head>

<body>
	<div id="box">
		<div id="box1" class="float">div1</div>
		<div id="box2" class="float">div2</div>
		<div id="box3" class="float">div3</div>
	</div>
</body>
</html>

效果图:

从上面现象,div1、div2、div3因设置了float:left;向左浮动了,但是最外层的div却没有被撑开,显示成了一条线,也就是最外层的div高度塌陷了。那什么情况一般会出现高度塌陷呢?

一般使父元素没有设置高度,而子元素都设置了浮动,此时父元素就会发生高度塌陷。

那么怎样去解决高度塌陷的问题呢?下面就总结几种清除浮动的方法。

1、给父级设置适当的高度

#box{
	width:400px;
	height:100px;
	border:1px solid blue;
}

效果图:

此方法只适合高度固定的布局。

2、结尾处加空div标签clear:both

html:

<div id="box">
	<div id="box1" class="float">div1</div>
	<div id="box2" class="float">div2</div>
	<div id="box3" class="float">div3</div>
	<div class="clear"></div>
</div>

css:

#box {
	width:400px;
	border:1px solid blue;
}
.float {
	width:100px;
	height:100px;
	float:left;
}
#box1 {
	background-color:red;
}
#box2 {
	background-color:green;
}
#box3 {
	background-color:yellow;
}
.clear {
	clear:both;
}

clear:left | right | both | none | inherit:元素的某个方向上不能有浮动元素 
clear:both:在左右两侧均不允许浮动元素。

3、父级div定义overflow:hidden

#box {
	width:400px;
	border:1px solid blue;
	overflow:hidden;
	zoom:1; //兼容IE6 IE7
}

4、使用after伪类清除浮动(主流,推荐使用)

html:

<div id="box" class="clearfix">
	<div id="box1" class="float">div1</div>
	<div id="box2" class="float">div2</div>
	<div id="box3" class="float">div3</div>
</div>

css:

.clearfix:after {
	content:".";
	clear:both;
	display:block;
	height:0;
	overflow:hidden;
	visibility:hidden;
	;
}
.clearfix {
	*zoom:1; /* IE/7/6*/
}

此种方法的写法很固定,一般可以写在一个公共的地方。

.clear:after{content:'';display:block;clear:both;height:0;overflow:hidden;visibility:hidden;}
.clear{zoom:1;}

对于不同清除浮动的方式,一般具体问题具体解决,以上只是介绍了几种主流以及兼容性比较好的方式。

好文推荐:http://www.cnblogs.com/zhongweizhu/p/6003537.html
http://www.cnblogs.com/AnotherLife/p/5800751.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值