html div css——清除浮动

清除浮动是前端开发初学者比较头疼的问题,下面就前辈经验和实际项目中用到的解决方法:

1.利用伪对象after方法(推荐)

定义一个样式类 clearfix,使用伪对象after,来控制浮动元素的影响。

.clearfix:after{ height:0;line-height:0; content:" "; display:block; visibility:hidden; clear:both;}

.clearfix{ zoom:1;}  //ie7兼容问题

把 clearfix 加入父级元素class即可。代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>清除浮动</title>
		<style type="text/css">
			.clearfix:after{height:0;line-height:0; content:" "; display:block; visibility:hidden; clear:both;}
			.clearfix{zoom:1;}  /*ie7兼容问题*/
			.container{width:400px;border:1px solid red;}
			.con_left{float: left;width: 100px;height: 100px;border:1px solid blue;}
			.con_right{float: right;width: 200px;height: 200px;border:1px solid deepskyblue;}
		</style>
	</head>
	<body>
		<div class="container clearfix">
			<div class="con_left"></div>
			<div class="con_right"></div>
		</div>
	</body>
</html>


2.对父级CSS选择器加overflow:hidden样式(注意:如果子元素使用定位布局,无效。)

代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>清除浮动</title>
		<style type="text/css">
			.overflow_h{overflow: hidden;}
			.container{width:400px;border:1px solid red;}
			.con_left{float: left;width: 100px;height: 100px;border:1px solid blue;}
			.con_right{float: right;width: 200px;height: 200px;border:1px solid deepskyblue;}
		</style>
	</head>
	<body>
		<div class="container overflow_h">
			<div class="con_left"></div>
			<div class="con_right"></div>
		</div>
	</body>
</html>


3.在父级“</div>”结束前,新加一个div对应选择器样式为“clear:both”

代码如下:

<span style="font-size:12px;"><!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>清除浮动</title>
		<style type="text/css">
			.clear_b{clear: both;}
			.container{width:400px;border:1px solid red;}
			.con_left{float: left;width: 100px;height: 100px;border:1px solid blue;}
			.con_right{float: right;width: 200px;height: 200px;border:1px solid deepskyblue;}
		</style>
	</head>
	<body>
		<div class="container">
			<div class="con_left"></div>
			<div class="con_right"></div>
			<div class="clear_b"></div>
		</div>
	</body>
</html></span>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值