css 中float属性及clear的释疑

float属性可以让元素脱离文档流,父元素中的子元素设置为float,则会导致父元素的高度塌陷。

<style type="text/css">
.father{                         /*没有给父元素定义高度*/
	background:#ccc; 
	border:1px dashed #999; 
}
.box01,.box02,.box03{ 
	height:50px; 
	line-height:50px; 
	background:#f9c; 
	border:1px dashed #999; 
	margin:15px; 
	padding:0px 10px;
	float:left;                 /*定义box01、box02、box03三个盒子左浮动*/
}
</style>
</head> 
<body>
<div class="father">
	<div class="box01">box01</div>
	<div class="box02">box02</div>
	<div class="box03">box03</div>
</div>
</body>
</html>

因为浮动元素脱离文档流,为了撑起父元素,通常可以在父元素内再增加一个块元素。

.box04{
	height: 100px;
	border-style: solid;
}
</style>
</head> 
<body>
<div class="father">
	<div class="box01">box01</div>
	<div class="box02">box02</div>
	<div class="box03">box03</div>
	<div class="box04">box04</div>
</div>

父元素的高度取决于box04的高度,则必须知道浮动元素的高度,并以此值来指定了box04的高度,显然不方便。

为解决此问题,可将box04设置清除浮动属性。清除浮动的意思是指,元素在左右不允许有浮动元素,如果左右存在浮动元素,元素自己就下移(不是将浮动元素下移)。

当clear属性设置为left,表示元素之前如果有左浮动元素,则元素本身下移到浮动元素之后。

.box04{ 
	width: 100px;
	border-style: solid; 
	clear:left;
}
</style>
</head> 
<body>
<div class="father">
	<div class="box01">box01</div>
	<div class="box02">box02</div>
	<div class="box03">box03</div>
	<div class="box04">a</div>
</div>

效果如下:

将box04的边框和文字隐去

.box04{  
	clear:left;
}
</style>
</head> 
<body>
<div class="father">
	<div class="box01">box01</div>
	<div class="box02">box02</div>
	<div class="box03">box03</div>
	<div class="box04"></div>
</div>

达到将父框撑起的效果,而且父框能够自动适合浮动框大小。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值