清除浮动的几种常用的方法

先来看设置浮动后,未清除的效果:


我们给父元素设置了背景颜色,但是由于浮动,此时没有背景颜色

<!DOCTYPE html>
<html>
<head>
	<title>清除浮动</title>
	<style type="text/css">
		.father{
			border: 1px solid red;
			background: #fc9;
		}
		.div1{
			width: 80px;
			height: 80px;
			background: red;
			float: left;
		}
		.div2{
			width: 80px;
			height: 80px;
			background: blue;
			float: left;
		}

	</style>
</head>
<body>
<div class="father">
    <div class="div1">1</div>
    <div class="div2">2</div>
</div>
</body>
</html>

接下来清除浮动:

方法一:


是给所有浮动标签后面加一个空标签元素,定义style为  clear:both

弊端;增加了无意义的标签,不利于后期维护


具体看代码

<!DOCTYPE html>
<html>
<head>
	<title>清除浮动</title>
	<style type="text/css">
		.father{
			border: 1px solid red;
			background: #fc9;
		}
		.div1{
			width: 80px;
			height: 80px;
			background: red;
			float: left;
		}
		.div2{
			width: 80px;
			height: 80px;
			background: blue;
			float: left;
		}
		/*方法一*/
		.clear{
			clear:both; 
			height: 0; 
			line-height: 0; 
			font-size: 0
		}

	</style>
</head>
<body>
<div class="father">
    <div class="div1">1</div>
    <div class="div2">2</div>
</div>
</body>
</html>
方法二:使用over-flow

具体是给浮动的父元素添加一个css属性  over-flow:auto;zoom:1或者over-flow:hidden;zoom:1  ,其中zoom:1是用来兼容IE6的

具体看代码

<!DOCTYPE html>
<html>
<head>
	<title>清除浮动</title>
	<style type="text/css">
		.outer{
			border: 1px solid red;
			background: #fc9;
			color: #fff; 
		}
		.div1{
			width: 80px;
			height: 80px;
			background: red;
			float: left;
		}
		.div2{
			width: 80px;
			height: 80px;
			background: blue;
			float: left;
		}

		/*方法二*/
		.over-flow{
    		overflow: hidden; 
    		zoom: 1; 
    		/*zoom: 1; 是在处理兼容性问题*/
		}
		.outer {
			zoom:1;
			/*==for IE6/7 Maxthon2==*/
		}
	</style>
</head>
<body>
<div class="outer over-flow">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <!-- <div class="clear"></div> -->
</div>
</body>
</html>
清除浮动后的效果图:


方法三:使用:after伪对象  ,此方法只适用于非IE浏览器,
关键点:

1  content属性是必须有的,可以为空,也可以是'.'

2  height设置为0;


具体看代码;

<!DOCTYPE html>
<html>
<head>
	<title>清除浮动</title>
	<style type="text/css">
		.outer{
			border: 1px solid red;
			background: #fc9;
			color: #fff; 
		}
		.div1{
			width: 80px;
			height: 80px;
			background: red;
			float: left;
		}
		.div2{
			width: 80px;
			height: 80px;
			background: blue;
			float: left;
		}

		/*方法三*/
		.outer:after {
			clear:both;
			content:'.';
			display:block;
			width: 0;
			height: 0;
			visibility:hidden;
			/*==for FF/chrome/opera/IE8==*/
		}   
		.outer {
			zoom:1;
			/*==for IE6/7 Maxthon2==*/
		}
	</style>
</head>
<body>
<div class="outer over-flow">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <!-- <div class="clear"></div> -->
</div>
</body>
</html>

效果图和上面一样:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值