1. 程式人生 > >css清除浮動產生影響的三種方式

css清除浮動產生影響的三種方式

清除浮動:

清除浮動不是不會浮動,只是消除浮動產生的不利影響

當父盒子沒有定義高度,巢狀在父盒子內部的子盒子發生浮動後,父盒子下邊的元素位置發生錯誤,即父盒子中的子元素脫標

1、額外標籤法

<div class="con fixclear">
	<div class="con-left"></div><!-- 浮動元素 -->
	<div class="con-right"></div><!-- 浮動元素 -->
	<div class="clear" style="clear:both"></div><!-- 新增的就是我 -->
</div>

clear: left | right | both; 

在最後一個浮動元素後面新增標籤 

2、給父元素使用overflow:hidden (bfc)

<div class="con fixclear" style="overflow:hidden"><!-- 我是父元素 -->
	<div class="con-left"></div><!-- 浮動元素 -->
	<div class="con-right"></div><!-- 浮動元素 -->
</div>

如果有內容超出了盒子的話,就不能使用它,因為超出的部分被隱藏掉了

3、偽元素清除浮動(推薦使用)

.fixclear:after{
			content: ".";
			display: block;
			visibility: hidden;
			line-height: 0;
			clear: both;
}
/* 相容ie瀏覽器 */
.fixclear{
	zoom: 1;
}

給浮動元素的父元素使用.clearfix即可

最後貼一下程式碼: 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.top{
			width: 500px;
			height: 100px;
			background: yellow;
		}
		.con{
			width: 500px;
			/* height: 300px; */
		}
		.con .con-left{
			width: 250px;
			height: 300px;
			float: left;
			background: red;
		}
		.con .con-right{
			width: 250px;
			height: 300px;
			background: green;
			float: right;
		}
		.bottom{
			width: 500px;
			height: 100px;
			background: black;
		}
		/* 偽元素清除浮動 */
		.fixclear:after{
			content: ".";
			display: block;
			visibility: hidden;
			line-height: 0;
			clear: both;
		}
		/* 相容ie瀏覽器 */
		.fixclear{
			zoom: 1;
		}
	</style>
</head>
<body>
	<div class="top"></div>
	<!-- 給父元素使用overflow:hidden (bfc) -->
	<div class="con fixclear" style="overflow:hidden"><!-- 我是父元素 -->
		<div class="con-left"></div><!-- 浮動元素 -->
		<div class="con-right"></div><!-- 浮動元素 -->
		<!-- 額外標籤清除浮動 -->
		<div class="clear" style="clear:both"></div><!-- 新增的就是我 -->
	</div>
	<div class="bottom"></div>
</body>
</html>