CSS清除浮動方法

來源:互聯網
上載者:User

標籤:導致   code   處理   pad   height   div   src   sky   width   

HTML結構

1 <div class="wrap">2     <div class="div1">1</div>3     <div class="div2">2</div>4     <div class="div3">3</div>5 </div>

CSS樣式

1 .wrap{margin:10px;padding20px;border:5px solid gray;background-color:#fff;}2 .div1{float:left;height:100px;width:100px;background-color:lightgray;}3 .div2{float:left;height:100px;width:100px;background-color:skyblue;}4 .div3{float:left;height:100px;width:100px;background-color:red;}

 可以看到外層wrap div的高度並沒有撐起來,這是因為內層元素浮動脫離了文字資料流而導致的,這時我們就需要清除浮動。下面介紹清除浮動的三種常用方法。

1.在最後一個內層元素後面添加空元素,使用clear:both

1 <div class="wrap">2     <div class="div1">1</div>3     <div class="div2">2</div>4     <div class="div3">3</div>5     <div class="clear"></div>6 </div>
1 .clear{clear:both;}

 

2.給外層元素添加overflow:hidden或者auto屬性。

1 .wrap{2     overflow:auto;3     zoom:1;/*處理相容性問題*/4 }

 

 

3.給外層元素添加虛擬元素after,利用after類比建立元素div.clear。(推薦使用,可以作為公用樣式)

1 <div class="wrap clearfix">2     <div class="div1">1</div>3     <div class="div2">2</div>4     <div class="div3">3</div>5 </div>
 1 .clearfix{ 2     zoom:1;/*處理ie相容問題*/ 3 } 4 .clearfix:after{ 5     display:block; 6     visibility:hidden; 7     content:‘.‘; 8     clear:both; 9     height:0;10     overflow:hidden;11 }

 

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.