css float與clear詳解

來源:互聯網
上載者:User
<pre name="code" class="html">

1.浮動的曆史

大家知道嗎?最早的浮動初衷就是為了實現文字環繞的效果,類似於一張圖片在左上方,然後其周圍都是文字環繞著它,這個情境相信大家都見過吧!然而,浮動衍生至今,我們需要用到它的地方已經太多太多,最常用的就是導航的實現,還有其它方面的應用,比如單側固定,另一側自適應等等(這在下面將會有例子),下面會分幾個方面對浮動做介紹。

2.浮動的影響

相信float屬性是前端工程師切圖必備的一個樣式效果,如果你沒用過, 呵呵!!!本文不針對你。大家在用得爽的同時,有沒有想過它會帶來的問題呢!沒錯,浮動就是一柄雙刃劍,用它來實現想要的效果是很爽,但是如果用的不當就會自食其惡果。

首先,大家要知道,任何加了float不為none屬性的元素,它的display都會變成block,也就是說浮動元素就是區塊層級元素,不管它本來是什麼!

其次,大家要明白,浮動會造成父元素的塌陷,有一種官方的說法就是BFC(block format context),至於為什麼會這樣,大家可以去查閱相關資料。那怎樣解決這種問題呢,自然就是清浮動了,也就是clear。

但是清浮動也不僅僅就是用clear一個屬性就完了,因為涉及到瀏覽器的相容性問題,標準而使用的方法就是下面這個方法:

.clearfix{*zoom:1;}.clearfix:after{display: table;clear: both;content: '';}

清楚浮動用這些屬性足以,而且相容IE7+以及其它W3C瀏覽器,這裡說下zoom屬性,這個屬性只在IE7及以下有效果。

3.浮動實現的效果

首先說說左側固定,右側自適應的布局,代碼及如下:

<style>body { font-size: 14px; background-color: #DDF3F7; color: #333; }.clearfix{*zoom:1;}.clearfix:after{display: table;clear: both;content: '';}.wrap{width: 500px;height: 30px;line-height: 30px;margin: 20px auto;}.left{float: left;width:100px;margin-right:10px;border: 1px solid #ddd;}.rightbox{margin-left: 115px;}</style></head><body><p class="wrap clearfix"><p class="left">我在左側我在左側我在左側我在左側我在左側我在左側我在左側我在左側</p><p class="rightbox">我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右我在右側我在右側我在右側我在右側我在右側我在右</p></body>


這樣不管最外層的p的寬度為多少,左側的寬度是不變的,只有右側的寬度會自動改變。

還有另外一種實現方法:

<style>body { font-size: 14px; color: #333; }.clearfix{*zoom:1;}.clearfix:after{display: table;clear: both;content: '';}.wrap{width: 500px;height: 30px;line-height: 30px;margin: 20px auto;}.left{float: left;margin-right:10px;border: 1px solid #ddd;}.rightbox{display: table-cell;*width: auto;*display: inline-block;}</style></head><body><p class="wrap clearfix"><p class="left">我在左側我在左側我在左側我在左側我</p><p class="rightbox">我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右側我在右</p></body>

第二個是根據左側的寬度右側自適應的例子,大家可以運行著看看。











相關文章

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.