清除浮動的幾種方式

效果圖如下:

清除浮動前:


清除浮動後:


以下方式中,浮動元素的父元素均沒有設置寬高


第一種方式:給浮動的元素的父元素加上overflow屬性

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.container{
			width: 100px;
			height: 100px;
			margin: 15px;
			background: #ccc
		}
		.item{
			width: 50px;
			height: 50px;
			float: left;
			margin: 10px;
			background: #666;
		}
		.test{
			overflow: hidden;
		}
	</style>
</head>
<body>
	<div class="test">
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
	</div>
	<div class="container"></div>
	<div class="container"></div>
	<div class="container"></div>
	<script>
		// 因爲overflow: hidden會觸發BFC。BFC的意思是,我這個元素裏面的子孫元素,不會影響外部元素的佈局(從BFC的本意來說,必須給浮動元素撐出高度)。overflow:hidden首先會計算height: auto;的真實高度,由於其觸發了BFC,需要包含子元素,所以高度不是0,而是子元素高度。這時overflow:hidden;才起到隱藏作用,不過父元素高度足夠大,所以子元素沒有被隱藏。
		
		// 形成 BFC 的條件 
		// 1、浮動元素,float 除 none 以外的值; 
		// 2、絕對定位元素,position(absolute,fixed); 
		// 3、display 爲以下其中之一的值 inline-blocks,table-cells,table-captions; 
		// 4、overflow 除了 visible 以外的值(hidden,auto,scroll)

	</script>
</body>
</html>


第二種方式:增加額外標籤

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.container{
			width: 100px;
			height: 100px;
			margin: 15px;
			background: #ccc
		}
		.item{
			width: 50px;
			height: 50px;
			float: left;
			margin: 10px;
			background: #666;
		}
		.clear{
			clear: both
		}
	</style>
</head>
<body>
	<div class="test">
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="clear"></div>
	</div>
	<div class="container"></div>
	<div class="container"></div>
	<div class="container"></div>
	<script>
		// 如上。在浮動元素之下再放一個標籤,加上clear: both,就可以清除浮動

	</script>
</body>
</html>


第三種方式:使用僞類元素來清除浮動

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.container{
			width: 100px;
			height: 100px;
			margin: 15px;
			background: #ccc
		}
		.item{
			width: 50px;
			height: 50px;
			float: left;
			margin: 10px;
			background: #666;
		}
		.test:after{
			/*設置內容爲空*/
			content: "";
			/*高度爲0*/
			height: 0;
			/*行高爲0*/
			line-height: 0;
			/*將文本轉爲塊級元素*/
			display: block;
			/*將元素隱藏*/
			visibility: hidden;
			/*清除浮動*/
			clear: both;
     }
    .test{
			/*爲了兼容IE*/
      zoom: 1
    }
	</style>
</head>
<body>
	<div class="test">
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
	</div>
	<div class="container"></div>
	<div class="container"></div>
	<div class="container"></div>
	<script>
		// 給浮動元素的父元素加上僞類,樣式如上所寫,就可以清除浮動
	</script>
</body>
</html>





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章