DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
CSS 屬性簡寫與選擇器優先級計算
編輯:CSS詳解     

精簡 CSS 有各種手段,其中最常用的一招是屬性簡寫;而讀懂別人的樣式表,則離不開優先級的計算規則。這兩件事一起理解,CSS 的維護成本會降不少。

常用屬性的簡寫形式

font

font 涵蓋字體、字級、行高等多個屬性,各自對應的預設值如下:

/* font 各屬性與默認值 */
font-variant: normal;
line-height: normal;
font-family: varies;
font-weight: normal;
font-style: normal;
font-size: medium;

依 W3C 規範,合併後的順序固定為 style、variant、weight、size/line-height、family:

/* 字體各屬性前後順序 */
font: [font-style] [font-variant] [font-weight] [font-size]/[line-height] [font-family];

實際寫起來像这样:

font: 14px Georgia, serif;
font: 14px/1.4 Georgia, serif;
font: italic lighter 14px/1.4 Georgia, serif;
font: italic small-caps lighter 14px/1.4 Georgia, serif;

一行取代一段,程式碼視覺上也俐落。唯一的不便是單獨查找某個屬性時比較費眼。

list

三個子屬性及其預設值:

list-style-type: disc;
list-style-image: none;
list-style-position: outside;

合併寫法:

/* list 屬性簡短寫法 */
list-style: [list-style-type] [list-style-position] [list-style-image];

/* 示例 */
list-style: none;
list-style: disc;
list-style: disc outside;
list-style: disc outside url(bg.png);

background

五個子屬性:

/* background 的各屬性及其默認值 */
background-attachment: scroll;
background-color: transparent;
background-position: top left;
background-repeat: repeat;
background-image: none;

合併寫法:

/* background 屬性簡短寫法 */
background: [background-color] [background-image] [background-repeat] [background-attachment] [background-position];

/* 示例 */
background: #777;
background: url(images/bg.png) 0 0;
background: #777 url(images/bg.png) repeat-x 0 0;
background: #777 url(images/bg.png) repeat-x fixed 0 0;

不同標籤對 background 簡寫的容忍度略有差異,遇到奇怪的行為時建議查閱官方文檔。

border

三個子屬性:border-width、border-style、border-color,預設皆為 none(寬度實為 medium)。合併寫法:

/* border 屬性簡短寫法 */
border: [border-width] [border-style] [border-color];

/* 示例 */
border: 1px solid #111;
border: 2px dotted #222;
border: 3px dashed #333;

四邊需要不同樣式時,仍可逐一指定:

border-bottom: 1px solid #777;
border-right: 2px solid #111;
border-left: 2px solid #111;
border-top: 1px solid #777;

要注意簡寫會把未指定的子屬性重設為初始值,這經常是「明明前面寫了 border-color,後面補個 border-width 顏色卻不見了」的原因。

選擇器優先級怎麼算

CSS 的全名是層疊樣式表。層疊意味著多段規則可以同時作用於同一元素——一段管顏色,一段管大小,最終疊加呈現。便利的代價是複雜:當多段規則同時改動同一個屬性時,誰說了算?

看這段樣式:

p { color: black; background-color: white; }
div.warning p { color: red; }
div#caution p { color: yellow; }
body#home div p { color: white; }

四組選擇器都指向 p,且都設了 color。瀏覽器最終會渲染哪一種顏色?後寫的會蓋掉先寫的嗎?

答案是:瀏覽器會計算各選擇器的優先級,取最高者。計算規則依序為:

1. 行內樣式(寫在元素 style 屬性上)優先級最高,任何外部樣式都無法覆蓋。

2. 數 ID 選擇器的個數,最多者勝。

3. ID 數相同(或皆為 0)時,把 class 選擇器、屬性選擇器(如 [type="submit"])、偽類選擇器(如 :hover)的個數加總,最多者勝。

4. 若仍相同,數標籤選擇器(如 p)與偽元素選擇器(如 :first-letter)的個數,最多者勝。

5. 以上都相同時,後出現的規則覆蓋先出現的規則。

實務上習慣把優先級寫成四位數字(ID, class, 標籤, 其他)方便比較。回頭看範例,四組分別是 0001、0012、0102、0103,因此最終 body#home div p 的白色勝出。另外要補充兩點:!important 會凌駕上述所有規則,而 :not() 這類結構性偽類的優先級,是依其參數內部最高的選擇器來計算的。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved