問題的由來:
在CSS規(guī)范中,浮動(dòng)定位是脫離元素正常流的。所以,只要含有浮動(dòng)元素的父容器,在顯示時(shí)不考慮子元素的位置,就當(dāng)它們不存在一樣。這就造成了顯示出來,父容器好像空容器一樣。
比如下面代碼:
1 <div class="box">
2 <div style="float:left;width:100px;height:100px;"></div>
3 <div style="float:right;width:100px;height:100px"></div>
4 </div>
在瀏覽器中一運(yùn)行,實(shí)際視圖是子元素顯示在父容器的外部。
解決方法一:添加空元素
在浮動(dòng)元素下面添加一個(gè)非浮動(dòng)的元素
代碼如下:
復(fù)制代碼
1 <div class="box">
2 <div style="float:left;width:100px;height:100px;"></div>
3 <div style="float:right;width:100px;height:100px;"></div>
4 <div class="clearfix"></div>
5 </div>
6
7 <style>
8 .clearfix{
9 clear:both;
10 }
11 </style>
復(fù)制代碼
解決方法二:浮動(dòng)的父容器
將父容器也改成浮動(dòng)定位,這樣它就可以帶著子元素一起浮動(dòng)了
代碼如下:
復(fù)制代碼
1 <div class="box">
2 <div style="float:left;width:100px;height:100px;"></div>
3 <div style="float:right;width:100px;height:100px;"></div>
4 </div>
5
6 <style>
7 .box{
8 float:left;
9 }
10 </style>
復(fù)制代碼
解決方法三:浮動(dòng)元素的自動(dòng)clearing
讓父容器變得可以自動(dòng)"清理"(clearing)子元素的浮動(dòng),從而能夠識(shí)別出浮動(dòng)子元素的位置,不會(huì)出現(xiàn)顯示上的差錯(cuò)。
代碼如下:
復(fù)制代碼
1 <div class="box">
2 <div style="float:left;width:100px;height:100px;"></div>
3 <div style="float:right;width:100px;height:100px;"></div>
4 </div>
5
6 <style>
7 .box{
8 overflow:hidden;
9 }
10 </style>
復(fù)制代碼
解決方法四:通過CSS語(yǔ)句添加子元素,這樣就不用修改HTML代碼
就是用after偽元素的方法在容器尾部自動(dòng)創(chuàng)建一個(gè)元素的方法
代碼如下:
復(fù)制代碼
1 <div class="box">
2 <div style="float:left;width:100px;height:100px;"></div>
3 <div style="float:right;width:100px;height:100px;"></div>
4 </div>
5
6 <style>
7 .box:after {
8 content: "\0020";
9 display: block;
10 height: 0;
11 clear: both;
12 zoom:1;
13 }
14 </style>