span有固定寬度

來源:互聯網
上載者:User

<html xmlns="http ://www.w3.org/1999/xhtml " > <head> <title>Test Span</title> <mce:style type="text/css"><!-- span { background-color:#ffcc00; width:150px ; } --></mce:style><style type="text/css" mce_bogus="1">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;}

 

很多人會建議再增加一個CSS 屬性 float ,這樣的確在某種條件下能解決問題。比如我們的例子中,如果span前面沒有文字
,那的確是可行的。但是如果有了,前後文字就會連在一起,而span跑到了第二行。span { background-color:#ffcc00;
display:block; float:left; width:150px;}

 

設定 span 寬度的完美解決方案

下面代碼的 CSS定義完美解決了span的寬度設定問題。由於瀏覽器通常對不支援的CSS屬性採取忽略處理的態度,所以最好將
display:inline -block行寫在後面,這樣在Firefox裡面,如果到了未來的Firefox
3,這一行就能起作用,代碼可以同時相容各種版本。

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head><title>Test Span</title> <mce:style type="text/css"><!-- span { background-color:#ffcc00; display:-moz-inline-box; display:inline-block; width:150px;} --></mce:style><style type="text/css" mce_bogus="1">span { background-color:#ffcc00; display:-moz-inline-box; display:inline-block; width:150px;}</style> </head> <body> fixed <span>width</span> span </body></html>

聯繫我們

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