CSS/选择器

维基教科书,自由的教学读本
< CSS

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 指定类别的元素的符合指定类别的所有后继兄弟元素适用相应风格