553
技術社區[雲棲]
缺省情況下span的寬度設定無效的解決方案
在html中如何設定span的寬度?這看上去是個很簡單的問題,似乎用style中的width屬性就可以。例如,- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="https://www.w3.org/1999/xhtml" >
- <head>
- <title>Test Span</title>
- <style type="text/css">
- span {
- background-color:#ffcc00;
- width:150px;
- }
- </style>
- </head>
- <body>
- fixed <span>width</span> span
- </body>
- </html>
通過試驗以後發現,無效,無論是在Firefox還是IE中都無效。
通過查閱CSS2標準中關於width的定義發現,原來CSS中的width屬性並不總是有效的,如果對象是inline對象,width屬性就會被忽略。Firefox和IE原來是遵循了標準才這樣做的。
修改span為block類型並設置float不是完美解決
在span的CSS中增加display屬性,將span設置為block類型的Element,這樣寬度的確有效了,不過也把前後文字隔在不同行裏麵。這樣其實span就完全變成了div。
- span {
- background-color:#ffcc00;
- display:block;
- width:150px;
- }
- span {
- background-color:#ffcc00;
- display:block;
- float:left;
- width:150px;
- }
-
-
button的情況
其實,在Html的各種Element中,的確有既是inline,又能夠設定寬度的情況存在。例如下麵代碼就顯示了button對象,就可以很好的在文字中間出現,並且設定寬度。
- <body>
- fixed <button style="width:150px;">width</button> button
- </body>
更新的標準CSS 2.1
再看更新的標準,在CSS2.1標準草案中display的定義中增加了一個叫inline-block的屬性值,針對的恰好是我們麵對的這種情形。那麼再看看各種瀏覽器的對應情況。
Firefox
通過display的文檔了解到,inline-block在未來的Firefox 3中會實現。通過Mozllia擴展屬性參考了解到,在Firefox 3以前的版本,例如現在的Firefox 2中,可以用-moz-inline-box達到同樣的效果。IE
通過MSDN中的display文檔了解到,inline-block已經實現。實際測試發現IE 6.0以後都沒問題。完美的解決方案
下麵代碼的CSS定義完美解決了span的寬度設置問題。由於瀏覽器通常對不支持的CSS屬性采取忽略處理的態度,所以最好將 display:inline-block行寫在後麵,這樣在Firefox裏麵,如果到了未來的Firefox 3,這一行就能起作用,代碼可以同時兼容各種版本。
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="https://www.w3.org/1999/xhtml" >
- <head>
- <title>Test Span</title>
- <style type="text/css">
- span {
- background-color:#ffcc00;
- display:-moz-inline-box;
- display:inline-block;
- width:150px;
- }
- </style>
- </head>
- <body>
- fixed <span>width</span> span
- </body>
- </html>
最後更新:2017-04-02 00:06:38