CSS的selector可翻譯為選擇器選取項,是出現在樣式規則的左大括號之前的部分。如" p { font-weight:bold; } "的p。選擇器指出樣式規則可用於哪個元素,可根據元素的類別type,如"div";元素的類class;元素的id。選擇器只能用於連結或嵌入CSS,不能用於內聯CSS。

選擇器概述
選擇器的分類 選擇器例子 規則例子 注釋
類別選擇器 type div div { margin:7px; padding:7px; }
類選擇器 class .important .important { font-weight:bold; color:red; }
id選擇器 #onlyThisOne #onlyThisOne { font-family:courier; }
一般選擇器 universal * * { color:green; }
擬類選擇器 pseudo-class a:link a:link { color:blue; } 偽類是特殊的類,基於元素的狀態,使用:運算符。語法為E:pseudo-class. 常見的有:hover, :link and :visited
擬元素選擇器 pseudo-element p:first-letter p:first-letter { color:red }
後代選擇器 descendant td span td span { font-weight:bold; }
群組選擇器 grouped h1, h2, h3 h1, h2, h3 { text-align:center; }
子選擇器(Child)
比鄰選擇器 (Adjacent)
屬性選擇器(Attribute) E[Attribute="value"] Attribute支持多種不同的匹配運算符,如 =, !=, ~=, ^= and $=

選擇器語法 編輯

選擇器是用組合器(combinator)分隔的一個或多個簡單選擇器序列組成的序列。一個擬元素(pseudo-element)可以出現在該序列的最後一個簡單選擇器中。

簡單選擇器序列(sequence of simple selectors)是不用組合器分隔的一個簡單選擇器鏈(chain of simple selectors)。它總是以類別選擇器或通用選擇器開始;鏈中不能再出現別的類別選擇器或通用選擇器。

簡單選擇器可以是:類別選擇器、通用選擇器、特性選擇器、類選擇器、id選擇器、擬類選擇器。

組合器(Combinator)可以是:空白符、大於號、加號、波浪號~。

選擇器從文檔樹中選擇匹配的元素。

群組選擇器 編輯

群組選擇器Grouping selectors是一個用逗號分割的選擇器的列表。

h1, h2, h3 { text-align:center; }

等價於

h1 { text-align:center; }
h2 { text-align:center; }
h3 { text-align:center; }

一個元素可以被多條規則選中:

 h1, h2, h3, h4, h5, h6 { color: white; background-color: red; }
 h1 { color: yellow; }

所有標題有紅色背景。Level 2–6 標題有白色文字。Level 1標題是黃色文字。

規則的順序非常重要。下例中所有標題都是白色文字:

 h1 { color: yellow; } 
 h1, h2, h3, h4, h5, h6 { color: white; background-color: red; }

簡單選擇器 編輯

選擇器(type, class, ID, universal, 擬類和擬元素)都是簡單選擇器。完整語法從左至右為:

  • 類別選擇器或通用選擇器
  • 零個或多個類選擇器、id選擇器、偽類選擇器(CSS2.1也允許特性選擇器)
  • 零個或多個擬元素選擇器

下屬都是簡單選擇器例子:

  p
  p.important
  p#navigation
  a:link
  p:first-line
  a:visited#homePage.menu2:first-letter
  *
  *#footer
  *.content.abstract
  *#mainArticle:first-letter

通用選擇器*如果不是唯一的選擇器,則可以省略不寫。如#footer等價於*#footer:first-line等價於*:first-line

類別選取項 type 編輯

基於元素的基本類別type匹配元素。

 div{
   margin:7px;
   padding:7px;
 }
 body{
   background-image:url("image.gif");
   font-size:.9em;
 }

通用選擇器Universal 編輯

適用於頁面全部元素:

 * {
   color:green;
 }

特性Attribute 選擇器 編輯

[attribute]選擇器用於選取帶有指定特性的元素。

  • 特性存在和值的選擇器
    • [att] 特性存在
    • [att=val] 特性的值等於"val".
    • [att~=val] 特性的值是空白符分隔的列表,列表中的一項等於"val". 如果"val"包含空格符或者為空,則不選擇任何元素
    • [att|=val] 特性的值或者就是"val"或者以"val"開頭後跟連字符"-" (U+002D)。這本來用於語言的subcode匹配。參見 :lang 擬類
  • 匹配子字符串的特性選擇器
    • [att^=val] 以val開頭的字符串
    • [att$=val] 以val結尾的字符串
    • [att*=val] 包含val字符串的特性的值

選擇同時具有多個特性的元素,例如: span[hello="Cleveland"][goodbye="Columbus"]

選擇多個不同特性中具有任意一個特性的元素,例如:span[hello="Cleveland"], span[goodbye="Columbus"]

下例選擇所有帶有 target 特性的 <a> 元素;

a[target] {
  background-color: yellow;
}

[attribute="value"] 選擇器用於選取帶有指定屬性和值的元素。下例選取所有帶有 target="_blank" 屬性的 <a> 元素:

a[target="_blank"] { 
  background-color: yellow;
}

[attribute~="value"] 選擇器選取屬性值包含指定詞的元素。值必須是完整或單獨的單詞;即必須是空格分隔的清單中的每個完整的詞。它匹配attribute="a value b";但不匹配attribute="a valueb"。下例選取 title 屬性包含 "flower" 單詞的所有元素:

[title~="flower"] {
  border: 5px solid yellow;
}

[attribute|="value"] 選擇器用於選取指定屬性以指定值開頭的元素。值必須是空格符分割開的完整或單獨的單詞。下例選取 class 屬性以 "top" 開頭的所有元素:

[class|="top"] {
  background: yellow;
}

[attribute^="value"] 選擇器用於選取指定屬性以指定值開頭的元素。值不必是完整單詞。下例選取 class 屬性以 "top" 開頭的所有元素:

[class^="top"] {
  background: yellow;
}

[attribute$="value"] 選擇器用於選取指定屬性以指定值結尾的元素。值不必是完整單詞。下例選取 class 屬性以 "test" 結尾的所有元素:

[class$="test"] {
  background: yellow;
}

[attribute*="value"] 選擇器選取屬性值包含指定子字符串的元素。值不必是完整的子字符串。它匹配attribute="a value b" 且匹配 attribute="a valueb"。下例選取 class 屬性包含 "te" 的所有元素:

[class*="te"] {
  background: yellow;
}

特性名字(attribute name)可以給出一個CSS限定名,即已經聲明的命名空間前綴後跟豎槓符(|)。無命名空間的特性名字等效於"|attr"。一個星號用於表示無論是否有命名空間。例如:

@namespace foo "http://www.example.com";
[foo|att=val] { color: blue }
[*|att] { color: yellow }
[|att] { color: green }
[att] { color: green }
/*
The first rule will match only elements with the attribute att in the "http://www.example.com" namespace with the value "val".

The second rule will match only elements with the attribute att regardless of the namespace of the attribute (including no namespace).

The last two rules are equivalent and will match only elements with the attribute att where the attribute is not in a namespace. */

類選擇器Class 編輯

HTML文檔的body中的所有元素都可具有class特性。這可用於辨識同一類別的元素。在HTML中,div.value 等效於 div[class~=value]。例如:

 The <code class="attribute">alt</code> attribute of the <code class="element">img</code>

可建立一個全局類:

 .important {
   font-weight:bold; color:red;
 }


HTML例子:

 <p class="important">Important Text</p>
 <p>Ordinary Text</p>
 <div class="important">Important Footnote</div>

繪製為:

Important Text

Ordinary Text

Important Footnote

第二種使用方式是和類別選擇器一起使用:

 p.right {
   float:right;
   clear:both
 }

HTML例子:

 <p class="right">Righty Righty</p>

繪製結果:

Righty Righty


一個元素可以屬於多個類:

 <p class="right">This paragraph belongs to the class 'right'.</p>
 <p class="important">This paragraph belongs to the class 'important'.</p>
 <p class="right important">This paragraph belongs to both classes.</p>

繪製效果:

This paragraph belongs to the class 'right'.

This paragraph belongs to the class 'important'.

This paragraph belongs to both classes.


類名應該描述類的目的,而不是繪製效果。因為設計者可能改變其繪製的想法。

 .red {color:blue}

多個類選擇器可用於選擇具有所有指定類的元素:

p.important.right {
  border: 2px dashed #666
}

繪製例子:

This paragraph belongs to the class 'right'.

This paragraph belongs to the class 'important'.

This paragraph belongs to both classes.


ID選擇器 編輯

ID選擇器用於選擇一個頁面中的唯一元素。也可以多個頁面有同名的元素,或者與後代選擇器並用。

CSS rule:

 #onlyThisOne {
   font-family:courier;
 }

HTML例子:

 <p id="onlyThisOne">Courier</p>

繪製為:

Courier

擬類選擇器Pseudo-Classes 編輯

CSS1 和 CSS2.1的擬類選擇器以單個冒號:開始。其名字是大小寫不敏感的,可以跟隨括號中的值。

擬類選擇器允許選擇文檔樹之外的信息或者其它簡單選擇器不能表達的信息。

擬類選擇器可以在簡單選擇器序列中使用多次。一些擬類選擇器是互斥的。

動態的擬類選擇器是指不能從文檔樹推導出的一些特性(characteristics ),這些特性隨著用戶訪問文檔,擬類可以獲得或者失去,如visited

CSS level 1 定義了3個擬類:

link
unvisited links
visited
visited links
active
active links。當你點擊一個連結時,它是active

可用於anchor (a) 元素.

 a:link{
   color:blue;
 }

 a:visited{
   color:purple;
 }

 a:active{
   color:red;
 }

CSS level 2.1引入了一批新的擬類選擇器:

first-child
匹配元素是父元素的第一個子元素
lang(C)
匹配元素的自然語言特性等於C或者在連字號-左邊等於C。C的大小寫不敏感。lang特性自動繼承到後代元素中;而用特性選擇器|=就不適用這些後代元素。
  • 用戶動作擬類選擇器:
hover
當用戶的滑鼠懸浮在元素之上
active
任何能夠是 'active' ,例如button – 當元素是active時應用該樣式.
focus
具有鍵盤輸入焦點的元素可用該樣式

例如:

  p:first-child {
    font-size:120%
  }

  span:lang(la) { /* render Latin text, e.g. per se, in italics */
    font-style:italic
  }

  li:hover { /* doesn't work in Internet Explorer */
    background-color:blue
  }

  input:active {
    color:red
  }

  input:focus {
    background-color:yellow
  }

first-child擬類例子在下文的descendant中給出.

可以同時指定多個擬類:

a:visited:hover {
  background-color:red
}

需要注意擬類應用的順序。例如,如需要已訪問過的連結為綠色除非用戶滑鼠懸浮其上時為黃色,則規則必須為如下順序:

 a:visited{
   color:green
 }

 a:hover{
   color:yellow
 }

如果上述順序翻轉過來,則已訪問的顏色比懸浮的顏色有更高優先級。

一些新的擬類選擇器:

  • :target 當前頁面的URL的#號之後的錨名稱元素自動具有target特性
  • UI元素狀態擬類:
    • :enabled
    • :disabled
    • :checked 適用於Radio 和 checkbox 元素
    • :indeterminate 既不是checked 也不是 unchecked,未來會實現。
  • 結構的擬類選擇器structural pseudo-classes。text或非元素的node都不參與以下的結構計數。
    • :root 在HTML 4,這總是HTML元素
    • :nth-child(an+b) 注意這裡的n相當於關鍵字,表示任意的非負整數。a和b指明為整數,表示把兄弟元素分組,每組|a|個元素,每組第一個元素的index為1,每組的第b個元素被選擇。此外, :nth-child()可用『odd』和『even』作為實參。『odd』等效於 2n+1, 『even』等效於 2n。
    • :nth-last-child(an+b) 從尾部算起。
    • :nth-of-type(an+b) 在sibling元素中以指定類別計數的選擇。
    • :nth-last-of-type(an+b)
    • :first-child pseudo-class 等價於 :nth-child(1) 表示在sibling元素中為第一個。
    • :last-child pseudo-class 等價於 :nth-last-child(1)
    • :first-of-type pseudo-class 表示在它的類別中是sibling元素的第一個。等價於:nth-of-type(1)
    • :last-of-type pseudo-class 等價於 :nth-last-of-type(1)
    • :only-child 沒有sibling。等價於:first-child:last-child 或:nth-child(1):nth-last-child(1)
    • :only-of-type 同一類別沒有sibling
    • :empty 沒有子節點。
tr:nth-child(2n+1) /* represents every odd row of an HTML table */
tr:nth-child(odd)  /* same */
tr:nth-child(2n+0) /* represents every even row of an HTML table */
tr:nth-child(even) /* same */

/* Alternate paragraph colours in CSS */
p:nth-child(4n+1) { color: navy; }
p:nth-child(4n+2) { color: green; }
p:nth-child(4n+3) { color: maroon; }
p:nth-child(4n+4) { color: purple; }

:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
:nth-child(10n+9)  /* Same */
:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */

/* When a=0, 'an'部分不需要,除非b部分已经忽略。这可简化为 :nth-child(b) */
foo:nth-child(0n+5)   /* represents an element foo that is the 5th child
                         of its parent element */
foo:nth-child(5)      /* same */

/*当a=1, 或 a=-1, 1可从规则忽略。下述4例等效: */
bar:nth-child(1n+0)   /* represents all bar elements, specificity (0,1,1) */
bar:nth-child(n+0)    /* same */
bar:nth-child(n)      /* same */
bar                   /* same but lower specificity (0,0,1) */

/*如果b=0, 则第a个元素被选择: */
tr:nth-child(2n+0) /* represents every even row of an HTML table */
tr:nth-child(2n) /* same */

/*下述例子展示了空格符的有效使用: */
:nth-child( 3n + 1 )
:nth-child( +3n - 2 )
:nth-child( -n+ 6)
:nth-child( +6 )

/*下述例子展示了空格符的无效使用: */
:nth-child(3 n)
:nth-child(+ 2n)
:nth-child(+ 2)

/*如果a和b均为0,则拟类表示无元素。*/

/*a和b可以为负值。但只有正值表示元素选择:*/
html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
                              counting from the last one */

/* To represent all h2 children of an XHTML body except the first and last, one could use the following selector:*/
body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
/*In this case, one could also use :not(), although the selector ends up being just as long:*/
body > h2:not(:first-of-type):not(:last-of-type)

/*The following selector represents a p element that is the first child of a div element:*/
div > p:first-child
/*This selector can represent the p inside the div of the following fragment:*/
<p> The last P before the note.</p>
<div class="note">
   <p> The first P inside the note.</p>
</div>
/*but cannot represent the second p in the following fragment:*/
<p> The last P before the note.</p>
<div class="note">
   <h2> Note </h2>
   <p> The first P inside the note.</p>
</div>

/*下述二者等价*/
* > a:first-child /* a is first child of any element */
a:first-child /* Same (assuming a is not the root element) */

/*p:empty is a valid representation of the following fragment:*/
<p></p>
/*foo:empty is not a valid representation for the following fragments:*/
<foo>bar</foo>
<foo><bar>bla</bar></foo>
<foo>this is not <bar>:empty</bar></foo>
not(X)是否定偽類,其參數X是一個簡單選擇器(不含:not自身,即不可以遞歸)。擬元素也不可以作為其參數。

特性選擇器 編輯

還可以基於標記的其他特性(attribute)來選擇:

  • [attr] 表示有此屬性名稱的網頁元素。
  • [attr=value] 表示有此屬性名稱,且屬性值為此值的網頁元素。
  • [attr~=value] 表示有此屬性名稱,且以空格分隔的屬性值列表中,為此值的網頁元素。
  • [attr|=value] 表示有此屬性名稱,且屬性值為此值,或者屬性值為:value-,的網頁元素。這種形式常用於匹配語言。例如:zh-cn zh-tw en-us
  • [attr^=value] 表示有此屬性名稱,且屬性值以此值開頭的網頁元素。
  • [attr$=value] 表示有此屬性名稱,且屬性值以此值結束的網頁元素。
  • [attr*=value] 表示有此屬性名稱,且屬性值包含此值的網頁元素。
  • [attr operator value i] 在方括號中結尾處,添加此字母,表示此屬性選擇器,對於字母大小寫不敏感。
  • [attr operator value s] 在方括號中結尾處,添加此字母,表示此屬性選擇器,對字母大小寫敏感。

例如:

/* Internal links, beginning with "#" */
a[href^="#"] {
  background-color: gold;
}

擬元素選擇器 編輯

擬元素選擇器用於挑選出文檔樹中沒有的結構(如塊元素的第一行、第一個字符)或者沒有的內容(如before或after)。

CSS1 和 CSS2.1的擬元素選擇器以單個冒號:開始,CSS3的擬元素選擇器以2個冒號::開始。

CSS3規定:擬元素選擇器只能在組合器(combinator)的最後出現且至多出現一次。

CSS level 1定義了2個逆元素:first-letterfirst-line,分別選擇要繪製元素的第一個字母和第一行。

 p:first-letter { color:red }

只能用一個擬元素選擇器且必須是選擇器鏈上的最後一個。first-line選擇器只能用於塊級元素、內聯塊、table標題和table的單元格.

first-child選擇器要求元素是其父元素的第一個子元素。 下例使用first-child選擇器。

CSS規則:

 div.content strong:first-child {
   color:red
 }

HTML例子:

 <div class="content">
   <p>Some <em>emphasized</em> text and some <strong>strongly emphasized</strong> text.</p>
   <p>Some <strong>strongly emphasized</strong> text and some <em>emphasized</em> text.</p>
 </div>

繪製效果:

Some emphasized text and some strongly emphasized text.

Some strongly emphasized text and some emphasized text.

需要注意:

  • 元素的前面即使有text,不影響它是first-child。因此第一段落的em元素和第二段落strong元素分別是相應段落的第一個子元素。
  • 只有元素滿足選擇器的所有部分,才會應用該風格規則。第一段落的strong元素是第二個子節點,因此不匹配strong:first-child選擇器。
  • first-of-type
  • last-of-type
  • nth-child
  • nth-of-type
  • CSS2.1增加了2個擬元素,beforeafter。即在指定元素之前或之後添加一些內容。

組合器Combinator 編輯

由多個簡單選擇器組合而成。

後代組合器Descendant combinator 編輯

語法為: Element Element

即以空白符分隔。空白符可以是:空格符(U+0020), "tab" (U+0009), "換行符" (U+000A), "回車符" (U+000D), "form feed" (U+000C)。

允許在指定元素內部任何深度的另一個指定元素。可以列出大於2個元素組成的祖先後代樹。這時出現的星號*代表任意類別的元素。

例如:p元素內部任何深度後代元素span為黑體,則CSS規則:

 p span{
   font-weight:bold;
 }

HTML例子:

 <p>Start of paragraph. <span>This span is bold.</span> Rest of paragraph.</p>
 <div>Start of division. <span>This span is normal.</span> Rest of division.</div>

繪製效果:

Start of paragraph. This span is bold. Rest of paragraph.

Start of division. This span is normal. Rest of division.

下例改變"navigation"列表中已經訪問過的連結的顏色。

CSS規則:

 ul#navigation a:visited {
   color:red
 }

HTML例子:

 <ul id="navigation">
   <li><a href="HomePage">Home</a></li>
   <li><a href="AnotherPage">A page you haven't visited yet.</a></li>
 </ul>

繪製效果:

  • Home
  • A page you haven't visited yet.

子元素組合器Child combinator 編輯

Element>Element 指定類別的元素內的所有指定類別的直接子元素

例如:

body > p

div ol>li p
<!-- 表示p是li的后代li是ol的子元素, ol是div的后代 -->

兄弟元素組合器Sibling combinators 編輯

非元素的node,如元素之間的text都被忽略不計數。

直接後繼兄弟組合器 Next-sibling combinator 編輯

Element+Element 指定類別的元素的符合指定類別的直接後繼兄弟元素適用相應風格

所有後續兄弟組合器Subsequent-sibling combinator 編輯

Element~Element 指定類別的元素的符合指定類別的所有後繼兄弟元素適用相應風格