css选择器

CSS 规范 翻译

选择符? :)

原文件: www.w3.org/TR/REC-CSS2/selector.html

5 Selectors

5 选择器

5.1 Pattern matching

5.1 符式匹配

In CSS, pattern matching rules determine which style rules apply to elements in the document tree. These patterns, called selectors, may range from simple element names to rich contextual patterns. If all conditions in the pattern are true for a certain element, the selector matches the element.

在 CSS中, 符式匹配规则决定文档树(document tree).中的元素使用哪个样式规则. 这些符式, 被称为 选择器, 有的只是简单的元素名字, 有的则是复杂的上下文关联的符式. 如果一个元素忙组符式中所有的情况, 那么我们称该选择器和该元素匹配.

The case-sensitivity of document language element names in selectors depends on the document language. For example, in HTML, element names are case-insensitive, but in XML they are case-sensitive.

选择器中文档元素名称是否大小写敏感取决于文档语言. 比如在HTML中, 元素的名字是大小写不敏感的, 而XML中则是敏感的.

The following table summarizes CSS2 selector syntax:

下面的表格概述了CSS2选择器的语法:

PatternMeaningDescribed in section
*Matches any element.
匹配所有元素
Universal selector
通用选择器
EMatches any E element (i.e., an element of type E).
匹配所有E元素(也就是说类型为E的元素)
Type selectors
类型选择器
E FMatches any F element that is a descendant of an E element.
匹配所有是E元素的后代的F元素
Descendant selectors
后代选择器
E > FMatches any F element that is a child of an element E.
匹配所有是E元素的孩子的F元素
Child selectors
子选择器
E:first-childMatches element E when E is the first child of its parent.
匹配所有是其父元素的第一个子元素的E元素
The :first-child pseudo-class
长子伪选择器

这个翻译不大好理解:)
E:link
E:visited
Matches element E if E is the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited).
匹配包含有超链接的元素, :link匹配尚未浏览的, :visited匹配浏览过的.
The link pseudo-classes
链接伪选择器
E:active
E:hover
E:focus
Matches E during certain user actions.
匹配某些用户动作下的下E元素
The dynamic pseudo-classes
动态伪选择器
E:lang(c) Matches element of type E if it is in (human) language c (the document language specifies how language is determined). The :lang() pseudo-class
E + FMatches any F element immediately preceded by an element E.
匹配处于E元素前一个的F元素
Adjacent selectors
邻元素选择器
E[foo]Matches any E element with the "foo" attribute set (whatever the value). Attribute selectors
属性选择器
E[foo="warning"]Matches any E element whose "foo" attribute value is exactly equal to "warning".
匹配"foo"属性的精确等于"warning"的E元素
Attribute selectors
属性选择器
E[foo~="warning"]Matches any E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "warning".
如果E元素的"foo"属性的值是以空格分隔的列表, 如果其中某个等于"warning", 则匹配E元素.
Attribute selectors
属性选择器
E[lang|="en"]Matches any E element whose "lang" attribute has a hyphen-separated list of values beginning (from the left) with "en". Attribute selectors
属性选择器
DIV.warningHTML only. The same as DIV[class~="warning"].
仅HTML. 等同于DIV[class~="warning"].
Class selectors
类选择器
E#myidMatches any E element ID equal to "myid".
匹配ID值等于"myid"的E元素.
ID selectors
ID选择器

5.2 Selector syntax

5.2 选择器语法

A simple selector is either a type selector or universal selector followed immediately by zero or more attribute selectors, ID selectors, or pseudo-classes, in any order. The simple selector matches if all of its components match.

简单选择器类型选择器 or 通用选择器 和后面紧接着的零个或是任意数目的属性选择器 , ID 选择器, 或是伪选择器组成, 紧接着的选择器可以是任意次序的. 简单选择器在所有部分都匹配的时候才匹配.

A selector is a chain of one or more simple selectors separated by combinators. Combinators are: whitespace, ">", and "+". Whitespace may appear between a combinator and the simple selectors around it.

选择器 由一个或多个简单选择器用连接符串接而成. 连接符 : 空格, ">", 和 "+". 空格可能出现在连接符和它两头的简单选择器之间.

The elements of the document tree that match a selector are called subjects of the selector. A selector consisting of a single simple selector matches any element satisfying its requirements. Prepending a simple selector and combinator to a chain imposes additional matching constraints, so the subjects of a selector are always a subset of the elements matching the rightmost simple selector.

文档树中匹配某个选择器的元素被称为该选择器的 目标(subjects). 由一个简单选择器组成的选择器匹配所有满足它要求的的元素. 在符式串前面加上一个简单选择器和连接符, 将加上附加的约束, 所以一个选择器的目标通常是最右侧简单选择器的匹配元素的子集.

One pseudo-element may be appended to the last simple selector in a chain, in which case the style information applies to a subpart of each subject.

伪元素 may be appended to the last simple selector in a chain, in which case the style information applies to a subpart of each subject. TODO

5.2.1 Grouping

5.2.1 组合

When several selectors share the same declarations, they may be grouped into a comma-separated list.

当一些选择器使用相同的声明时, 它们可以组合一起到一个逗号分隔的的列表.

Example(s):

In this example, we condense three rules with identical declarations into one. Thus,

在这个例子中, 我们把三个相同的规则精简为一个. 所以,

H1 { font-family: sans-serif }
H2 { font-family: sans-serif }
H3 { font-family: sans-serif }

is equivalent to:

等同于:

H1, H2, H3 { font-family: sans-serif }

CSS offers other "shorthand" mechanisms as well, including multiple declarations and shorthand properties.

CSS 同样提供了其他的"简写"方式,包括 多项声明 and 简写属性.

5.3 Universal selector

5.3 通用选择器

The universal selector, written "*", matches the name of any element type. It matches any single element in the document tree.

通用选择器, 写作 "*", 匹配任何元素类型的名称. 匹配 文档树 中任何单个的元素.

If the universal selector is not the only component of a simple selector, the "*" may be omitted. For example:

如果通用选择器不是 简单选择器中唯一个的组成部分, "*" 可以被忽略. 比如:

  • *[LANG=fr] and [LANG=fr] are equivalent.
  • *.warning and .warning are equivalent.
  • *#myid and #myid are equivalent.
  • *[LANG=fr] [LANG=fr] 是相等的.
  • *.warning.warning 是相等的.
  • *#myid#myid 是相等的.

5.4 Type selectors

5.4 类型选择器

A type selector matches the name of a document language element type. A type selector matches every instance of the element type in the document tree.

类型选择器 匹配某个文档语言的元素类型. 类型选择器匹配文档树中所有该类型的的对象.

Example(s):

The following rule matches all H1 elements in the document tree:

Example(s):

下面的规则匹配文档树中所有的的H1元素:

H1 { font-family: sans-serif }

5.5 Descendant selectors

5.5 后代元素选择器

At times, authors may want selectors to match an element that is the descendant of another element in the document tree (e.g., "Match those EM elements that are contained by an H1 element"). Descendant selectors express such a relationship in a pattern. A descendant selector is made up of two or more selectors separated by whitespace. A descendant selector of the form "A B" matches when an element B is an arbitrary descendant of some ancestor element A.

有时, 文档编辑者可能希望选择器能匹配某个元素的后代元素, (e.g., "匹配被 H1 元素包含的 EM 元素"). 后代元素选择器 的符式用来表达这种关系. 一个后代元素选择器由一个或是多个选择器组成, 选择器之间用 whitespace分隔. 当B祖先 元素 A的任意代的后代元素时, "A B" 这样格式的选择器匹配元素B.

Example(s):

For example, consider the following rules:

举例, 请看下面的规则:

H1 { color: red }
EM { color: red }

这些规则的意图是通过改变字体颜色来强调文字, 但是在下面的情况, 强调的效果体现不出来:

(分开时, H1 和 EM 元素能达到强调的效果, 但是放一起的时候, EM的强调效果就体现不出来了)

<H1>This headline is <EM>very</EM> important</H1>

We address this case by supplementing the previous rules with a rule that sets the text color to blue whenever an EM occurs anywhere within an H1:

为了处理这种情况, 我们给上面的规则再补充一条, 当 EM 出现在 H1 元素中, 不管在任何位置, 都把 EM 元素的颜色设置为蓝色:

H1 { color: red }
EM { color: red }
H1 EM { color: blue }

The third rule will match the EM in the following fragment:

第三条规则将匹配下面片段中的 EM 元素:

<H1>This <SPAN class="myclass">headline 
is <EM>very</EM> important</SPAN></H1>

Example(s):

The following selector:

下面的选择器:

DIV * P 

matches a P element that is a grandchild or later descendant of a DIV element. Note the whitespace on either side of the "*".

匹配DIV元素的孙子辈和孙子辈以后的P元素. 注意"*"左右的空格.

Example(s):

The selector in the following rule, which combines descendant and attribute selectors, matches any element that (1) has the "href" attribute set and (2) is inside a P that is itself inside a DIV:

Example(s):

下面规则中的选择器由后代元素选择器和 属性选择器组合而成, 匹配此类元素: (1) 有一个 "href" 属性, 并且 (2) 在一个 P 元素中, P元素又在一个 DIV 元素中:

DIV P *[href]

5.6 Child selectors

5.6 子元素选择器

A child selector matches when an element is the child of some element. A child selector is made up of two or more selectors separated by ">".

子元素选择器 匹配某个元素的 元素. 子元素选择器由两个或更多的选择器组成, 用 ">" 分隔.

Example(s):

The following rule sets the style of all P elements that are children of BODY:

下面规则设置所有作为 BODY 元素子元素的P元素的样式:

BODY > P { line-height: 1.3 }

Example(s):

The following example combines descendant selectors and child selectors:

下面的例子混合了后代元素选择器和子元素选择器:

DIV OL>LI P

It matches a P element that is a descendant of an LI; the LI element must be the child of an OL element; the OL element must be a descendant of a DIV. Notice that the optional whitespace around the ">" combinator has been left out.

这个选择器匹配某个 P 元素, 该P元素必须是某个 LI 元素的后代元素; 该 LI 元素必须是某个 OL 元素的子元素; 该 OL 子元素必须是某个 DIV元素的后代元素. 注意, 在">"两侧的可选的空格被省略了.

For information on selecting the first child of an element, please see the section on the :first-child pseudo-class below.

关于如何选择某个元素的第一个子元素, 请查看下面" :first-child 伪类" 的章节.

5.7 Adjacent sibling selectors

5.7 邻元素选择器

Adjacent sibling selectors have the following syntax: E1 + E2, where E2 is the subject of the selector. The selector matches if E1 and E2 share the same parent in the document tree and E1 immediately precedes E2.

邻元素选择器语法格式如下: E1 + E2, 其中 E2 是目标元素. 当 E1 和 E2 在文档树中有相同的父元素并且 E2 紧接在 E1 后面时, 该选择器匹配 E2.

In some contexts, adjacent elements generate formatting objects whose presentation is handled automatically (e.g., collapsing vertical margins between adjacent boxes). The "+" selector allows authors to specify additional style to adjacent elements.

在某些情况下, 邻近的元素会生成一些格式化的对象, 这些对象的显示是自动控制的. ??? (e.g., 压缩相邻box之间的垂直间距). "+" 选择器允许网页编写者对邻近的元素指定附加的样式.

Example(s):

Thus, the following rule states that when a P element immediately follows a MATH element, it should not be indented:

因此, 下面的规则规定, 当一个 P 元素紧跟在一个 MATH 元素后面时, 它应当不缩进:

MATH + P { text-indent: 0 } 

The next example reduces the vertical space separating an H1 and an H2 that immediately follows it:

下一个例子减少了H1和H2之间的垂直间距, 当H2紧跟在H1后面时:

H1 + H2 { margin-top: -5mm }   

Example(s):

The following rule is similar to the one in the previous example, except that it adds an attribute selector. Thus, special formatting only occurs when H1 has class="opener":

下面的例子和上面的有些类似, 它加入了一个属性选择器. 因此, 指定的格式只在 H1 元素的 class="opener"时生效:

H1.opener + H2 { margin-top: -5mm }   

5.8 Attribute selectors

5.8 属性选择器

CSS2 allows authors to specify rules that match attributes defined in the source document.

CSS2 允许文档编写者指定属性规则, 这些规则通过文档源代码中定义的元素的属性来进行匹配.

5.8.1 Matching attributes and attribute values

5.8.1 属性匹配和属性值

Attribute selectors may match in four ways:

属性选择器可以通过四种方法来进行匹配:

[att]
Match when the element sets the "att" attribute, whatever the value of the attribute.
当元素设置了"att"属性时匹配, 不管属性的值是什么.
[att=val]
Match when the element's "att" attribute value is exactly "val".
当元素的属性精确的等于"val"时匹配.
[att~=val]
Match when the element's "att" attribute value is a space-separated list of "words", one of which is exactly "val". If this selector is used, the words in the value must not contain spaces (since they are separated by spaces).
当元素的"att"属性值是以空格分隔的"word"列表时, 只要其中一个精确等于"val", 规则就匹配. 当使用这种选择器时, "val"中不能包含空格 (因为空格是用来分隔的) 这儿应该是这个意思吧
[att|=val]
Match when the element's "att" attribute value is a hyphen-separated list of "words", beginning with "val". The match always starts at the beginning of the attribute value. This is primarily intended to allow language subcode matches (e.g., the "lang" attribute in HTML) as described in RFC 1766 ( [RFC1766]).
当元素的"att"属性值是以"-"分隔的"word"列表时, 如果以"val"开始, 那么规则匹配. 通常从属性值的开头开始匹配. 这主要是为了允许 语言子码 匹配 (e.g., HTML中的"lang"属性), 语言子码的描述参见RFC 1766 ( [RFC1766]). not understand

Attribute values must be identifiers or strings. The case-sensitivity of attribute names and values in selectors depends on the document language.

属性必须为标识符或是字符串. 选择器中属性的名称和值是否大小写敏感取决于文档使用的语言.

Example(s):

For example, the following attribute selector matches all H1 elements that specify the "title" attribute, whatever its value:

举例, 下面的属性选择器匹配所有指定了"title"属性的 H1 元素, 不管"title"属性的值是什么:

H1[title] { color: blue; }

Example(s):

In the following example, the selector matches all SPAN elements whose "class" attribute has exactly the value "example":

在下面的例子中, 选择器匹配的是所有"class"属性精确等于"example"的 SPAN 元素:

SPAN[class=example] { color: blue; }

Multiple attribute selectors can be used to refer to several attributes of an element, or even several times the same attribute.

可以对于同一个元素的多个属性使用多个属性选择器, 甚至是对同一个属性使用多个属性选择器.

Example(s):

Here, the selector matches all SPAN elements whose "hello" attribute has exactly the value "Cleveland" and whose "goodbye" attribute has exactly the value "Columbus":

这儿, 这个选择器匹配所有 "hello" 属性精确等于 "Cleveland" 同时 "goodbye" 属性也精确等于 "Columbus" 的 SPAN 元素:

SPAN[hello="Cleveland"][goodbye="Columbus"] { color: blue; }

Example(s):

The following selectors illustrate the differences between "=" and "~=". The first selector will match, for example, the value "copyright copyleft copyeditor" for the "rel" attribute. The second selector will only match when the "href" attribute has the value "http://www.w3.org/".

下面的选择器说明了 "=" 和 "~=" 的不同. 举例, 第一选择器会匹配"rel"属性值为 "copyright copyleft copyeditor" 的元素. 第二个选择器只会匹配 "href" 属性值为 "http://www.w3.org/" 的元素.

A[rel~="copyright"]
A[href="http://www.w3.org/"]

Example(s):

The following rule hides all elements for which the value of the "lang" attribute is "fr" (i.e., the language is French).

下面的规则会隐藏所有"lang"属性值为"fr"的元素 (举例, 语言为法语).

*[LANG=fr] { display : none }

Example(s):

The following rule will match for values of the "lang" attribute that begin with "en", including "en", "en-US", and "en-cockney":

下面的规则会匹配所有以"en"打头的"lang"属性值, 包括 "en", "en-US", 和 "en-cockney":

*[LANG|="en"] { color : red }

Example(s):

Similarly, the following aural style sheet rules allow a script to be read aloud in different voices for each role:

类似地, 下面的语音样式表的规则可以让某个剧本里的不同角色用不同的声音来朗读:

DIALOGUE[character=romeo] 
     { voice-family: "Lawrence Olivier", charles, male }
      
DIALOGUE[character=juliet]  
     { voice-family: "Vivien Leigh", victoria, female }

5.8.2 Default attribute values in DTDs

5.8.2 DTD中默认的属性值

Matching takes place on attribute values in the document tree. For document languages other than HTML, default attribute values may be defined in a DTD or elsewhere. Style sheets should be designed so that they work even if the default values are not included in the document tree.

匹配针对的属性值是文档树中的属性值. 对于除HTML之外的那些文档语言, 默认的属性值可能定义在一个 DTD 中或其他地方. 样式表应该设计成在默认值没有包含在文档树中的情况下也能正常工作.

Example(s):

For example, consider an element EXAMPLE with an attribute "notation" that has a default value of "decimal". The DTD fragment might be

举例, 一个元素 EXAMPLE 有一个属性 "notation", 该属性的默认值是 "decimal". 在 DTD 中的片段可能如下:

<!ATTLIST EXAMPLE notation (decimal,octal) "decimal">;

If the style sheet contains the rules

如果样式表包含了一下规则

EXAMPLE[notation=decimal] { /*... default property settings ...*/ }
EXAMPLE[notation=octal] { /*... other settings...*/ }

then to catch the cases where this attribute is set by default, and not explicitly, the following rule might be added:

接着, 为了匹配属性为默认值的情况, 可能会加入下面的规格 , (不是直白的办法)

EXAMPLE { /*... default property settings ...*/ }

Because this selector is less specific than an attribute selector, it will only be used for the default case. Care has to be taken that all other attribute values that don't get the same style as the default are explicitly covered.

因为该选择器没有不像属性选择器一样 明确指定, 它将只用于默认情况. 需要注意, 所有其他的和默认属性值不同的属性值都要明确的指定规则.

5.8.3 Class selectors

5.8.3 类选择器

For style sheets used with HTML, authors may use the dot (.) notation as an alternative to the "~=" notation when matching on the "class" attribute. Thus, for HTML, "DIV.value" and "DIV[class~=value]" have the same meaning. The attribute value must immediately follow the ".".

在用于HTML的样式表中, 在匹配"class"属性时, 编写者可能使用点号(.)作为 "~=" 符号的另一种写法. 因此, 对于HTML, "DIV.value" 和 "DIV[class~=value]" 具有相同的意思. 属性值需要紧跟在"."后面.

Example(s):

For example, we can assign style information to all elements with class~="pastoral" as follows:

举例, 我们像下面这样可以对所有 class~="pastoral" 的元素指定样式:

*.pastoral { color: green }  /* all elements with class~=pastoral */
or just 或者只是
.pastoral { color: green }  /* all elements with class~=pastoral */

The following assigns style only to H1 elements with class~="pastoral":

下面的只对 class~="pastoral"的H1元素指定样式:

H1.pastoral { color: green }  /* H1 elements with class~=pastoral */

Given these rules, the first H1 instance below would not have green text, while the second would:

在这些规则下, 第一个H1对象不会使用绿色的文字, 第二则会:

<H1>Not green</H1>
<H1 class="pastoral">Very green</H1>

To match a subset of "class" values, each value must be preceded by a ".", in any order.

为了匹配"class"属性值的子集, 每个值的前面都需要加一个".", 顺序任意

Example(s):

For example, the following rule matches any P element whose "class" attribute has been assigned a list of space-separated values that includes "pastoral" and "marine":

举例, 下面的规则匹配那些 "class" 属性是一个以空格分隔的列表, 其中包含"pastoral" 和 "marine"的P元素:

 
P.pastoral.marine { color: green }

This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".

该规则匹配 class="pastoral blue aqua marine" 但是不匹配class="pastoral blue".

Note. CSS gives so much power to the "class" attribute, that authors could conceivably design their own "document language" based on elements with almost no associated presentation (such as DIV and SPAN in HTML) and assigning style information through the "class" attribute. Authors should avoid this practice since the structural elements of a document language often have recognized and accepted meanings and author-defined classes may not.

注意. CSS 中class属性的功能非常强大 , 以至于页面编辑者可以 conceivably 设计出自己的"文档语言" based on elements with almost no associated presentation (such as DIV and SPAN in HTML) and assigning style information through the "class" attribute. 页面编辑者应该避免这种实践行为, 因为 the structural elements of a document language often have recognized and accepted meanings and author-defined classes may not.

5.9 ID selectors

5.9 ID 选择器

Document languages may contain attributes that are declared to be of type ID. What makes attributes of type ID special is that no two such attributes can have the same value; whatever the document language, an ID attribute can be used to uniquely identify its element. In HTML all ID attributes are named "id"; XML applications may name ID attributes differently, but the same restriction applies.

文档语言可能包含声明为"ID"的属性. makes attributes of type ID special is that no two such attributes can have the same value; whatever the document language, an ID attribute can be used to uniquely identify its element. In HTML all ID attributes are named "id"; XML applications may name ID attributes differently, but the same restriction applies.

The ID attribute of a document language allows authors to assign an identifier to one element instance in the document tree. CSS ID selectors match an element instance based on its identifier. A CSS ID selector contains a "#" immediately followed by the ID value.

The ID attribute of a document language allows authors to assign an identifier to one element instance in the document tree. CSS ID selectors match an element instance based on its identifier. A CSS ID selector contains a "#" immediately followed by the ID value.

Example(s):

The following ID selector matches the H1 element whose ID attribute has the value "chapter1":

H1#chapter1 { text-align: center }

In the following example, the style rule matches the element that has the ID value "z98y". The rule will thus match for the P element:

<HEAD>
  <TITLE>Match P</TITLE>
  <STYLE type="text/css">

    *#z98y { letter-spacing: 0.3em }
  </STYLE>
</HEAD>
<BODY>
   <P id=z98y>Wide text</P>
</BODY>

In the next example, however, the style rule will only match an H1 element that has an ID value of "z98y". The rule will not match the P element in this example:

<HEAD>
  <TITLE>Match H1 only</TITLE>
  <STYLE type="text/css">
    H1#z98y { letter-spacing: 0.5em }
  </STYLE>

</HEAD>
<BODY>
   <P id=z98y>Wide text</P>
</BODY>

ID selectors have a higher precedence than attribute selectors. For example, in HTML, the selector #p123 is more specific than [ID=p123] in terms of the cascade.

ID selectors have a higher precedence than attribute selectors. For example, in HTML, the selector #p123 is more specific than [ID=p123] in terms of the cascade.

Note. In XML 1.0 [XML10], the information about which attribute contains an element's IDs is contained in a DTD. When parsing XML, UAs do not always read the DTD, and thus may not know what the ID of an element is. If a style sheet designer knows or suspects that this will be the case, he should use normal attribute selectors instead: [name=p371] instead of #p371. However, the cascading order of normal attribute selectors is different from ID selectors. It may be necessary to add an "!important" priority to the declarations: [name=p371] {color: red ! important}. Of course, elements in XML 1.0 documents without a DTD do not have IDs at all.

5.10 Pseudo-elements and pseudo-classes

5.10 伪元素伪类

In CSS2, style is normally attached to an element based on its position in the document tree. This simple model is sufficient for many cases, but some common publishing scenarios may not be possible due to the structure of the document tree. For instance, in HTML 4.0 (see [HTML40]), no element refers to the first line of a paragraph, and therefore no simple CSS selector may refer to it.

CSS introduces the concepts of pseudo-elements and pseudo-classes to permit formatting based on information that lies outside the document tree.

  • Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element's content. CSS pseudo-elements allow style sheet designers to refer to this otherwise inaccessible information. Pseudo-elements may also provide style sheet designers a way to assign style to content that does not exist in the source document (e.g., the :before and :after pseudo-elements give access to generated content).
  • Pseudo-classes classify elements on characteristics other than their name, attributes or content; in principle characteristics that cannot be deduced from the document tree. Pseudo-classes may be dynamic, in the sense that an element may acquire or lose a pseudo-class while a user interacts with the document. The exception is ':first-child', which can be deduced from the document tree.

Neither pseudo-elements nor pseudo-classes appear in the document source or document tree.

Pseudo-classes are allowed anywhere in selectors while pseudo-elements may only appear after the subject of the selector.

Pseudo-elements and pseudo-class names are case-insensitive.

Some pseudo-classes are mutually exclusive, while others can be applied simultaneously to the same element. In case of conflicting rules, the normal cascading order determines the outcome.

Conforming HTML user agents may ignore all rules with :first-line or :first-letter in the selector, or, alternatively, may only support a subset of the properties on these pseudo-elements.

5.11 Pseudo-classes

5.11.1 :first-child pseudo-class

The :first-child pseudo-class matches an element that is the first child of some other element.

Example(s):

In the following example, the selector matches any P element that is the first child of a DIV element. The rule suppresses indentation for the first paragraph of a DIV:

DIV > P:first-child { text-indent: 0 }
This selector would match the P inside the DIV of the following fragment:
<P> The last P before the note.
<DIV class="note">
   <P> The first P inside the note.

</DIV>
but would not match the second P in the following fragment:
<P> The last P before the note.
<DIV class="note">
   <H2>Note</H2>
   <P> The first P inside the note.

</DIV>

Example(s):

The following rule sets the font weight to 'bold' for any EM element that is some descendant of a P element that is a first child:

P:first-child EM { font-weight : bold }

Note that since anonymous boxes are not part of the document tree, they are not counted when calculating the first child.

For example, the EM in:

<P>abc <EM>default</EM> 
is the first child of the P.

The following two selectors are equivalent:

* > A:first-child   /* A is first child of any element */
A:first-child       /* Same */

5.11.2 The link pseudo-classes: :link and :visited

User agents commonly display unvisited links differently from previously visited ones. CSS provides the pseudo-classes ':link' and ':visited' to distinguish them:

  • The :link pseudo-class applies for links that have not yet been visited.
  • The :visited pseudo-class applies once the link has been visited by the user.

Note. After a certain amount of time, user agents may choose to return a visited link to the (unvisited) ':link' state.

The two states are mutually exclusive.

The document language determines which elements are hyperlink source anchors. For example, in HTML 4.0, the link pseudo-classes apply to A elements with an "href" attribute. Thus, the following two CSS2 declarations have similar effect:

A:link { color: red }
:link  { color: red }

Example(s):

If the following link:

<A class="external" href="http://out.side/">external link</A>

has been visited, this rule:
A.external:visited { color: blue }
will cause it to be blue.

5.11.3 The dynamic pseudo-classes: :hover, :active, and :focus

Interactive user agents sometimes change the rendering in response to user actions. CSS provides three pseudo-classes for common cases:

  • The :hover pseudo-class applies while the user designates an element (with some pointing device), but does not activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not supporting interactive media do not have to support this pseudo-class. Some conforming user agents supporting interactive media may not be able to support this pseudo-class (e.g., a pen device).
  • The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.
  • The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).

These pseudo-classes are not mutually exclusive. An element may match several of them at the same time.

CSS doesn't define which elements may be in the above states, or how the states are entered and left. Scripting may change whether elements react to user events or not, and different devices and UAs may have different ways of pointing to, or activating elements.

User agents are not required to reflow a currently displayed document due to pseudo-class transitions. For instance, a style sheet may specify that the 'font-size' of an :active link should be larger than that of an inactive link, but since this may cause letters to change position when the reader selects the link, a UA may ignore the corresponding style rule.

Example(s):

 

A:link    { color: red }    /* unvisited links */
A:visited { color: blue }   /* visited links   */
A:hover   { color: yellow } /* user hovers     */
A:active  { color: lime }   /* active links    */

Note that the A:hover must be placed after the A:link and A:visited rules, since otherwise the cascading rules will hide the 'color' property of the A:hover rule. Similarly, because A:active is placed after A:hover, the active color (lime) will apply when the user both activates and hovers over the A element.

Example(s):

An example of combining dynamic pseudo-classes:

A:focus { background: yellow }
A:focus:hover { background: white }

The last selector matches A elements that are in pseudo-class :focus and in pseudo-class :hover.

For information about the presentation of focus outlines, please consult the section on dynamic focus outlines.

Note. In CSS1, the ':active' pseudo-class was mutually exclusive with ':link' and ':visited'. That is no longer the case. An element can be both ':visited' and ':active' (or ':link' and ':active') and the normal cascading rules determine which properties apply.

5.11.4 The language pseudo-class: :lang

If the document language specifies how the human language of an element is determined, it is possible to write selectors in CSS that match an element based on its language. For example, in HTML [HTML40], the language is determined by a combination of the "lang" attribute, the META element, and possibly by information from the protocol (such as HTTP headers). XML uses an attribute called XML:LANG, and there may be other document language-specific methods for determining the language.

The pseudo-class ':lang(C)' matches if the element is in language C. Here C is a language code as specified in HTML 4.0 [HTML40] and RFC 1766 [RFC1766]. It is matched the same way as for the '|=' operator.

Example(s):

The following rules set the quotation marks for an HTML document that is either in French or German:

HTML:lang(fr) { quotes: '« ' ' »' }
HTML:lang(de) { quotes: '»' '«' '/2039' '/203A' }
:lang(fr) > Q { quotes: '« ' ' »' }
:lang(de) > Q { quotes: '»' '«' '/2039' '/203A' }

The second pair of rules actually set the 'quotes' property on Q elements according to the language of its parent. This is done because the choice of quote marks is typically based on the language of the element around the quote, not the quote itself: like this piece of French “à l'improviste” in the middle of an English text uses the English quotation marks.

5.12 Pseudo-elements

5.12.1 The :first-line pseudo-element

The :first-line pseudo-element applies special styles to the first formatted line of a paragraph. For instance:

P:first-line { text-transform: uppercase }

The above rule means "change the letters of the first line of every paragraph to uppercase". However, the selector "P:first-line" does not match any real HTML element. It does match a pseudo-element that conforming user agents will insert at the beginning of every paragraph.

Note that the length of the first line depends on a number of factors, including the width of the page, the font size, etc. Thus, an ordinary HTML paragraph such as:

<P>This is a somewhat long HTML 
paragraph that will be broken into several 
lines. The first line will be identified
by a fictional tag sequence. The other lines 
will be treated as ordinary lines in the 
paragraph.</P>
the lines of which happen to be broken as follows:
THIS IS A SOMEWHAT LONG HTML PARAGRAPH THAT
will be broken into several lines. The first
line will be identified by a fictional tag 
sequence. The other lines will be treated as 
ordinary lines in the paragraph.
might be "rewritten" by user agents to include the fictional tag sequence for :first-line. This fictional tag sequence helps to show how properties are inherited.
<P><P:first-line> This is a somewhat long HTML 
paragraph that will </P:first-line> be broken into several
lines. The first line will be identified 
by a fictional tag sequence. The other lines 
will be treated as ordinary lines in the 
paragraph.</P>

If a pseudo-element breaks up a real element, the desired effect can often be described by a fictional tag sequence that closes and then re-opens the element. Thus, if we mark up the previous paragraph with a SPAN element:

<P><SPAN class="test"> This is a somewhat long HTML
paragraph that will be broken into several
lines.</SPAN> The first line will be identified
by a fictional tag sequence. The other lines 
will be treated as ordinary lines in the 
paragraph.</P>
the user agent could generate the appropriate start and end tags for SPAN when inserting the fictional tag sequence for :first-line.
<P><P:first-line><SPAN class="test"> This is a
somewhat long HTML
paragraph that will </SPAN></P:first-line><SPAN class="test"> be
broken into several
lines.</SPAN> The first line will be identified
by a fictional tag sequence. The other lines
will be treated as ordinary lines in the 
paragraph.</P>

The :first-line pseudo-element can only be attached to a block-level element.

The :first-line pseudo-element is similar to an inline-level element, but with certain restrictions. Only the following properties apply to a :first-line pseudo-element: font properties, color properties, background properties, 'word-spacing', 'letter-spacing', 'text-decoration', 'vertical-align', 'text-transform', 'line-height', 'text-shadow', and 'clear'.

5.12.2 The :first-letter pseudo-element

The :first-letter pseudo-element may be used for "initial caps" and "drop caps", which are common typographical effects. This type of initial letter is similar to an inline-level element if its 'float' property is 'none', otherwise it is similar to a floated element.

These are the properties that apply to :first-letter pseudo-elements: font properties, color properties, background properties, 'text-decoration', 'vertical-align' (only if 'float' is 'none'), 'text-transform', 'line-height', margin properties, padding properties, border properties, 'float', 'text-shadow', and 'clear'.

 

The following CSS2 will make a drop cap initial letter span two lines:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
 <HEAD>
  <TITLE>Drop cap initial letter</TITLE>

  <STYLE type="text/css">
   P              { font-size: 12pt; line-height: 12pt }
   P:first-letter { font-size: 200%; font-style: italic;
                    font-weight: bold; float: left }
   SPAN           { text-transform: uppercase }
  </STYLE>
 </HEAD>
 <BODY>
  <P><SPAN>The first</SPAN> few words of an article
    in The Economist.</P>

 </BODY>
</HTML>

This example might be formatted as follows:

Image illustrating the combined effect of the :first-letter and :first-line pseudo-elements   [D]

The fictional tag sequence is:

<P>
<SPAN>
<P:first-letter>
T
</P:first-letter>he first
</SPAN> 
few words of an article in the Economist.
</P>

Note that the :first-letter pseudo-element tags abut the content (i.e., the initial character), while the :first-line pseudo-element start tag is inserted right after the start tag of the element to which it is attached.

In order to achieve traditional drop caps formatting, user agents may approximate font sizes, for example to align baselines. Also, the glyph outline may be taken into account when formatting.

Punctuation (i.e, characters defined in Unicode [UNICODE] in the "open" (Ps), "close" (Pe), and "other" (Po) punctuation classes), that precedes the first letter should be included, as in:

Quotes that precede the
first letter should be included.   [D]

The :first-letter pseudo-element matches parts of block-level elements only.

Some languages may have specific rules about how to treat certain letter combinations. In Dutch, for example, if the letter combination "ij" appears at the beginning of a word, both letters should be considered within the :first-letter pseudo-element.

Example(s):

The following example illustrates how overlapping pseudo-elements may interact. The first letter of each P element will be green with a font size of '24pt'. The rest of the first formatted line will be 'blue' while the rest of the paragraph will be 'red'.

P { color: red; font-size: 12pt }
P:first-letter { color: green; font-size: 200% }
P:first-line { color: blue }


<P>Some text that ends up on two lines</P>

Assuming that a line break will occur before the word "ends", the fictional tag sequence for this fragment might be:

<P>
<P:first-line>

<P:first-letter> 
S 
</P:first-letter>ome text that 
</P:first-line> 
ends up on two lines 
</P>

Note that the :first-letter element is inside the :first-line element. Properties set on :first-line are inherited by :first-letter, but are overridden if the same property is set on :first-letter.

5.12.3 The :before and :after pseudo-elements

The ':before' and ':after' pseudo-elements can be used to insert generated content before or after an element's content. They are explained in the section on generated text.

Example(s):

 

H1:before {content: counter(chapno, upper-roman) ". "}

When the :first-letter and :first-line pseudo-elements are combined with :before and :after, they apply to the first letter or line of the element including the inserted text.

Example(s):

 

P.special:before {content: "Special! "}
P.special:first-letter {color: #ffd800}

This will render the "S" of "Special!" in gold.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值