清除浮動(dòng)的原理和方法

2022-04-16    分類: 網(wǎng)站建設(shè)

問題的由來:

在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語句添加子元素,這樣就不用修改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>

當(dāng)前名稱:清除浮動(dòng)的原理和方法
當(dāng)前鏈接:http://www.bm7419.com/news39/145739.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、ChatGPT小程序開發(fā)、品牌網(wǎng)站建設(shè)、定制開發(fā)商城網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)