浮動元素脫離文檔流夕土,不占據(jù)空間。浮動元素碰到包含它的邊框或者浮動元素的邊框停留瘟判。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.float-div div{
width: 100px;
height: 100px;
margin: 20px;
/*文字內(nèi)容垂直水平居中寫法*/
text-align: center;
line-height: 100px;
/**/
background-color:#FFFF99;
/*浮動*/
float: left;
}
.normal-div{
width: 100px;
height: 100px;
line-height: 100px;
/**/
background-color:#CCCCFF;
}
</style>
</head>
<body>
<div class="float-div">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div class="normal-div">A</div>
</body>
</html>
原版圖
1.添加空div標(biāo)簽怨绣,并設(shè)置樣式 clear: both
在浮動元素的后面添加一個空 div 兄弟元素,利用 css 提高的 clear:both 清除浮動拷获,讓父級 div 能自動獲 取到高度
缺點:如果頁面浮動布局多篮撑,就要增加很多空 div,讓人感覺很不好 .
<div class="float-div">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div class="clear-both"></div>
<div class="normal-div">A</div>
.clear-both {
clear: both;
}
2.父級標(biāo)簽定義偽類 ::after
.float-div::after {
content: '';
height: 0;
/**/
display: block;
clear: both;
}
3.父級標(biāo)簽增加樣式 overflow:hidden
父級 div 定義 overflow:hidden 超出盒子部分會被隱藏匆瓜,不推薦使用.
.float-div {
overflow: hidden;
}
4.父級 div 定義 height
原理:父級 div 手動定義 height承璃,就解決了父級 div 無法自動獲取到高度的問題。
優(yōu)缺點:簡單雹熬、代碼少、容易掌握 捻脖,但 只適合高度固定的布局.
5.父級 div 定義 偽類:after 和 zoom
原理:IE8 以上和非 IE 瀏覽器才支持:after,原理和方法 1 有點類似,zoom(IE 轉(zhuǎn)有屬性)可解決 ie6,ie7 浮動問題 .
推薦使用纸型,建議定義公共類,以減少 CSS 代碼梅忌。
.float-div:after{
/*//設(shè)置內(nèi)容為空
//高度為0
//行高為0
//將文本轉(zhuǎn)為塊級元素
//將元素隱藏
//清除浮動*/
content: "";
height: 0;
line-height: 0;
display: block;
visibility: hidden;
clear: both;
}
.float-div{
/*為了兼容IE*/
zoom:1;
}
清除浮動-效果圖
備注:清除浮動的幾種方式