CSS的width:100%和width:auto區別

來源:互聯網
上載者:User

CSS的width:100%和width:auto區別

一、   問題

前段時間在調整樹結構的時候,發現如果樹的節點名稱比較長的話在IE6下則不會撐開外面的元素,導致節點的名稱只顯示了一半,同時表徵圖和名稱換行顯示了,但是在IE8和IE9下則顯示正常。定位到問題後,最終發現是下面的屬性導致的,如紅色所致,把width的值設定為auto後即可解決問題:

 
 

.TreeView,.TreeView ul{ 

    padding:0px 0px 0px  19px; 

    list-style:none; 

    margin:0px 0px; 

    width:100%;/*這裡修改為auto*/ 

    background:url(./trstree-default-line.gif)  repeat-y 0px  center ;

}

 

二、   結論

[1] width:100% 並不包含margin-left  margin-right的屬性值,直接取其父容器的寬度加上含margin-left /margin-right的值。如果設定了margin那新的width值是容器的寬度加上margin的值。(細心觀察)就會發現加了  margin相對應的邊就會多出設定的空白。而且會多出橫向捲軸因為寬度已經超出了螢幕的範圍。(這條相對於父容器是body)。

[2] width:auto包含margin-left/margin-right的屬性值。其值包含margin-left /margin-right的值。width:auto總是佔據整行!!!這其中margin的值已經包含其中了(也就是一整行)如果要設定margin的值那就用一整行然後減去margin的值就得到了現在的寬度了。減去的這個值就是相應邊得空白。顯著的特徵是這個沒有橫向捲軸出現也就是寬度沒有增加。

[3] 在IE6下顯示不正常,但是在IE8和IE9下顯示正常,可能是IE8和IE9對width:100%的解析與IE6不同所致,但是兩者對width:auto的解析是一致的。

相關文章

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.