清除浮動的原理和方法,清除浮動原理方法

來源:互聯網
上載者:User

清除浮動的原理和方法,清除浮動原理方法

問題的由來:

在CSS規範中,浮動定位是脫離元素正常流的。所以,只要含有浮動元素的父容器,在顯示時不考慮子項目的位置,就當它們不存在一樣。這就造成了顯示出來,父容器好像空容器一樣。

比如下面代碼:

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>

在瀏覽器中一運行,實際視圖是子項目顯示在父容器的外部。

解決方案一:添加空元素

在浮動元素下面添加一個非浮動的元素

代碼如下:

 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>

解決方案二:浮動的父容器

將父容器也改成浮動定位,這樣它就可以帶著子項目一起浮動了

代碼如下:

 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>

解決方案三:浮動元素的自動clearing

讓父容器變得可以自動"清理"(clearing)子項目的浮動,從而能夠識別出浮動子項目的位置,不會出現顯示上的差錯。

代碼如下:

 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>

解決方案四:通過CSS語句添加子項目,這樣就不用修改HTML代碼

就是用after虛擬元素的方法在容器尾部自動建立一個元素的方法

代碼如下:

 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>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.