css權重簡單之談

來源:互聯網
上載者:User

原來回複51js上面一個兄弟的問題,害怕在茫茫的資訊之海中會被淹沒,暫時轉到這兒來,以示學習總結之意。

在回答別人問題時,對自己真是一個考驗提高,在總結,摸清原有模糊概念的基礎上要講,全,簡,易。真是不容易。佩服那些寫教程福利芸芸眾生的先行者們~!!

下面簡單談談css的權重:
權重簡單的也可以理解為JavaScript中的範圍,回頭仔細想想,其實所有的IT抽象世界的東東都是通的。
內嵌樣式 > 內部樣式表 > 外聯樣式表
如:<head>
<link href="main.css" rel="stylesheet" type="text/css" />
<style>
.txt{color:blue;}
</style>
</head>
<p class="txt" style="color:red">這是一個測試文本</p>

main.css中:

.txt{color:green}

這三個裡邊:

內嵌樣式:

style="color:red" 

內部樣式表:<style>
.txt{color:blue;}
</style>

外聯樣式表:

main.css
中內容。
這是大體上的css權重量層級,一般常用外聯。
然後我們在看常用的main.css中權重層級:
在main.css 中:
id選取器的權重是大於類別選取器的權重。
如:#test{color:red;}
.test{color:blue;}

其中#test的大於.test的權重。
另外如果在一個css檔案中出現兩個同命的css屬性值,那會怎麼樣呢?當然跟其它物件導向程式語言中的,覆蓋相似,下面的屬性會覆蓋掉上面的屬性。如:.test2{color:red;border:1px solid #ccc;}
.test2{color:blue;font-size:14px;}

這樣最終應用到DOM元素上的樣式是:color:blue;font-size:14px;border:1px solid #ccc;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br /><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><br /><head><br /><title>豪情</title><br /><meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /><br /><style type="text/css"><br />*{margin:0;padding:0;font-size:12px;}<br />.test2{color:red;border:1px solid #ccc;}<br />.test2{color:blue;font-size:14px;}<br /></style><br /></head><br /><body><br /><div class="test2">這是一個test2的內容</div><br /></body><br /></html><br />

運行代碼

還有一種情況是層次選取器下面權重的延伸,這種情況是用js操作動態效果時可以節省不少js代碼,在邏輯上面來說,展現與行為的分離也是盡善盡美。.txt{color:blue;}
#wrap .txt{color:red;font-size:14px;}

如:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br /><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><br /><head><br /><title>豪情</title><br /><meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /><br /><style type="text/css"><br />*{margin:0;padding:0;font-size:12px;}<br />.txt{color:blue;}<br />#wrap .txt{color:red;font-size:14px;}<br /></style><br /><head><br /><body><br /><div class="txt">這是一個txt文本</div><br /><div id="wrap"><br /><div class="txt">這又是一個txt文本</div><br /></div><br /></body><br /></html><br />

運行代碼

相關文章

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.