css 清除浮動的方法

來源:互聯網
上載者:User

標籤:原理   一個   round   使用   意義   htm   增加   設定   width   

不添加清除浮動的時候:這裡我沒有給最外層的DIV.outer 設定高度,但是我們知道如果它裡面的元素不浮動的話,那麼這個外層的高是會自動被撐開的。但是當內層元素浮動後,就出現了一下影響:
(1):背景不能顯示 (2):邊框不能撐開 (3):margin 設定值不能正確顯示
<style>
.outer {
border: 1px solid red;
width: 400px;
}
.inner{
width:50px;
height:50px;
background-color:green;
margin-right:20px;
float:left;
}
.footer{
width:400px;
height:100px;
background-color: purple;
}
</style>
<div class="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>
<div class="footer"></div>

清除浮動方法1:添加新的元素,給他的css 添加clear:both
 在浮動元素的父級內部所有浮動元素的後面一個空標籤,給他的樣式寫clear:both;
  弊端:添加了新的無意義的標籤

.claer{clear:both;height:0;line-height:0;font-size:0}
<div class="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
 <div class="clear"></div>
</div>

方法二:父級div定義 overflow: auto或者hidden(注意:是父級div也就是這裡的  div.outer)

  此方法有效地解決了通過空標籤元素清除浮動而不得不增加無意代碼的弊端。

  不過使用overflow的時候,可能會對頁面表現帶來影響,而且這種影響是不確定的,你最好是能在多個瀏覽器上測試你的頁面;

.over-flow{
overflow: hidden;
  zoom:1 //用於相容IE6
}<div class="outer over-flow">
  <div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<!--<div class="clear"></div>-->
</div>
<div class="footer"></div>

方法三: 據說是最高大上的方法  :after 方法:(注意:作用於浮動元素的父親)

   先說原理:這種方法清除浮動是現在網上最拉風的一種清除浮動,他就是利用:after和:before來在元素內部插入兩個元素塊,從面達到清除浮動的效果。其實現原理類似於clear:both方法,只是區別在於:clear在html插入一個div.clear標籤,而outer利用其偽類clear:after在元素內部增加一個類似於div.clear的效果。下面來看看其具體的使用方法:   

.outer{
zoom:1 /* // 相容IE6/7 */
}
.outer:after{
clear:both;
content:‘.‘;
display:block;
width:0;
height:0;
visibility:hidden; /*允許瀏覽器渲染他,但是不顯示出來*/
}
其中clear:both;指清除所有浮動;content: ‘.‘; display:block;對於FF/chrome/opera/IE8不能缺少,其中content()可以取值也可以為空白。visibility:hidden;的作用是允許瀏覽器渲染它,但是不顯示出來,這樣才能實現清楚浮動。

 

  

css 清除浮動的方法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.