CSS 清除浮动的三种方式

1.浮动元素的父级元素如果定义了高度,就不需要清除浮动了。(新闻的内容长短不确定,高度不确定,就需要清除浮动)

2.浮动元素要定义宽高,否则会影响后续元素的浮动效果。


空div标签清除浮动.html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.header,.main,.footer{
			width:500px;

		}
		.header,.footer{
			height: 100px;
			background: #000;
		}
		.main{
			background: #eee;
			margin: 10px 0;
		}
		.content{
			width: 300px;
			height: 300px;
			background: orange;
			float: left;
		}
		.sidebar{
			width: 190px;
			height: 300px;
			background: green;
			float: right;
		}

	</style>
</head>
<body>
	<div class="header"></div>
	<div class="main">
		<div class="content"></div>
		<div class="sidebar"></div>
		<div style="clear:both;"></div>   <!--在最后的浮动元素后,用空的div标签清除浮动-->
	</div>

	<div class="footer"></div>
</body>
</html>
父标签的overflow清除浮动.html:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.header,.main,.footer{
			width:500px;

		}
		.header,.footer{
			height: 100px;
			background: #000;
		}
		.main{
			background: #eee;
			margin: 10px 0;
			overflow:hidden;   /*浮动元素的父级标签 overflow属性清除浮动。(bfc) (弊端:超出父元素之外的内容会隐藏) */
		}
		.content{
			width: 300px;
			height: 300px;
			background: orange;
			float: left;
		}
		.sidebar{
			width: 190px;
			height: 300px;
			background: green;
			float: right;
		}

	</style>
</head>
<body>
	<div class="header"></div>
	<div class="main">
		<div class="content"></div>
		<div class="sidebar"></div>
	</div>

	<div class="footer"></div>
</body>
</html>
伪元素清除浮动.html(建议使用该方法):
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.header,.main,.footer{
			width:500px;
		}
		.header,.footer{
			height: 100px;
			background: #000;
		}
		.main{
			background: #eee;
			margin: 10px 0;
		}
		.content{
			width: 300px;
			height: 300px;
			background: orange;
			float: left;
		}
		.sidebar{
			width: 190px;
			height: 300px;
			background: green;
			float: right;
		}
		.clearfix:after{  /*伪元素清除浮动。父级元素引用clearfix类*/
			content:".";  /*可以为空*/
			display: block;
			height: 0;
			line-height: 0;
			visibility: hidden;
			clear:both;  /*清除浮动*/
		}
		.clearfix{  /*兼容ie浏览器*/
			zoom:1;
		}
	</style>
</head>
<body>
	<div class="header"></div>
	<div class="main clearfix">    <!--浮动标签的父级元素引用clearfix类-->
		<div class="content"></div>
		<div class="sidebar"></div>
	</div>

	<div class="footer"></div>
</body>
</html>

伪元素清除浮动的另一种写法.css:

.clearfix:before, .clearfix:after {
    content: "";
    display: table;
}

.clearfix:after {
    clear: both;
}

.clearfix {
    *zoom: 1; /*IE/7/6*/
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值