이 문서는 Selectors Level 3 (W3C Recommendation 29 September 2011)의 한국어 번역본입니다.
이 문서에 오역 및 오타를 포함할 수 있습니다. 가능하면 원문도 확인하시길 바랍니다.

공개일
2015-10-07
번역자:
조은 <apes0123@gmail.com>

W3C

셀렉터 레벨 3

2011년 9월 29일 W3C 권고안

이 버전:
http://www.w3.org/TR/2011/REC-css3-selectors-20110929/
최신 버전:
http://www.w3.org/TR/css3-selectors/
최신 셀렉터 스펙 문서:
http://www.w3.org/TR/selectors/
이전 버전:
http://www.w3.org/TR/2009/PR-css3-selectors-20091215/
Editors:
Tantek Çelik (Invited Expert)
Elika J. Etemad (Invited Expert)
Daniel Glazman (Disruptive Innovations SARL)
Ian Hickson (Google)
Peter Linss (former editor, Netscape/AOL)
John Williams (former editor, Quark, Inc.)

스펙 문서의 규범적인 정의에 수정이 있을 가능성이 있기 때문에 errata도 확인하시길 바랍니다

번역본도 있습니다.


개요

셀렉터는 트리 요소에 매치하는 패턴이며 XML 문서에서 노드를 선택할 때 사용하는 방법 중 하나입니다. 셀렉터는 HTML이나 XML에서 사용하는 것에 최적화 되어있으며 성능이 중요한 코드에서 사용하기 쉽게 설계하였습니다.

Selectors are patterns that match against elements in a tree, and as such form one of several technologies that can be used to select nodes in an XML document. Selectors have been optimized for use with HTML and XML, and are designed to be usable in performance-critical code.

CSS (Cascading Style Sheets)는 HTMLXML 문서가 스크린, 종이 매체, 음성 매체 등에서 렌더링 되는 방법을 정의하는 언어입니다. CSS는 문서 내의 요소에 style 속성을 묶어주기 위해 셀렉터를 사용합니다.

CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents on screen, on paper, in speech, etc. CSS uses Selectors for binding style properties to elements in the document.

이 문서는 CSS1 [CSS1]CSS2 [CSS21]에 이미 존재하던 셀렉터에 CSS3 및 다른 언어에서 필요로 하는 셀렉터를 소개합니다.

This document describes the selectors that already exist in CSS1 [CSS1] and CSS2 [CSS21], and further introduces new selectors for CSS3 and other languages that may need them.

셀렉터는 아래 함수를 정의합니다:

Selectors define the following function:

expression ∗ element → boolean

즉 요소와 셀렉터가 주어졌을 때, 그 요소가 어떤 셀렉터에 매치하는 지 이 스펙문서에서 정의합니다.

That is, given an element and a selector, this specification defines whether that element matches the selector.

이 식은 일련의 요소 혹은 요소 그룹 안의 자식 요소, 서브트리 안 모든 요소에 대해 식을 계산하여 선택할 때 사용합니다. XML 트리 변환 언어 STTS (Simple Tree Transformation Sheets)는 이 메커니즘을 이용합니다. [STTS3]

These expressions can also be used, for instance, to select a set of elements, or a single element from a set of elements, by evaluating the expression across all the elements in a subtree. STTS (Simple Tree Transformation Sheets), a language for transforming XML trees, uses this mechanism. [STTS3]

이 문서의 상태

이 섹션은 이 문서를 공개했을 때 상태에 대해 설명합니다. 다른 문서가 이 문서를 덮어쓸 가능성이 있으니 주의하시길 바랍니다. 이 문서 및 W3C에서 공개한 다른 문서의 최신 버전은 W3C technical reports index at http://www.w3.org/TR/에서 확인 가능합니다.

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

이 문서는 CSS Working Group에서 제공하는 후보 권고안입니다. 역주: 현재 권고안이나 PR때 문서가 그대로 권고안이 되었습니다.

This document was produced by the CSS Working Group as a Proposed Recommendation.

W3C 권고안은, 구현 가능하도록 광범위하게 리뷰를 받은 뒤 공개한 성숙한 문서입니다. 이 스펙문서와 관련한 토론은 (archived) 공개 메일링 리스트 www-style@w3.org (참가안내서)에서 하는 것이 바람직하며, 메일을 보낼 때에는 제목에 “css3-selectors”를 기입해주시길 바랍니다. 이는 곧, “[css3-selectors] …본문 요약…” 같은 형태일 것입니다.

A W3C Recommendation is a mature document that has been widely reviewed and has been shown to be implementable. W3C encourages everybody to implement this specification. Comments may be sent to the (archived) public mailing list www-style@w3.org (see instructions). When sending e-mail, please put the text “css3-selectors” in the subject, preferably like this: “[css3-selectors] …summary of comment…

이 문서는 W3C 멤버, 소프트웨어 개발자, 그리고 다른 W3C 그룹 및 관계자들이 평가를 진행하여, 디렉터에 의해 W3C 권고안으로 발표했습니다. 이 문서는 안정적이며, 참고자료로 사용하거나 다른 문서에서 인용해도 좋습니다. 스펙 문서의 권고를 통해 W3C가 하는 역할은 스펙 문서에 관심을 모으고 다방면으로 퍼뜨리는 일입니다. 이를 통해 웹의 기능과 상호운용성 향상을 기대할 수 있습니다.

This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.

이 문서는 2004년 2월 6일 W3C 특허 정책을 따르는 그룹에서 작성하였습니다. W3C는 그룹의 성과물에 관련하여 모든 공개 특허 공개 리스트를 관리합니다. 여기에는 특허 공개에 대한 지시사항도 포함합니다. 특허에 대해서 충분한 지식이 있는 사람이, 스펙 문서의 Essential Claim(s)에 인정된다고 파악되는 경우, W3C 특허 정책 제 6장에 의거하여 정보를 공개해야 할 필요가 있습니다.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

이 스펙문서에 대한 여러개의 구현체 및 test suite를 포함한 구현보고서를 제공합니다.

A separate implementation report contains a test suite and shows several implementations of the specification.

이 문서는 보여지는 부분에 대한 편집내용 변경, 참고문서 업데이트를 제외하곤, 이전 버전의 후보 권고안과 동일합니다.

This document is the same as the previous, Proposed Recommendation version, except for editorial changes to the front matter, and updating of references.

목차

1. 소개

셀렉터 레벨 1과 셀렉터 레벨 2는 CSS1CSS2.1에서 각자 기능적으로 정의한 셀렉터의 서브셋을 정의하였습니다.

Selectors Level 1 and Selectors Level 2 are defined as the subsets of selector functionality defined in the CSS1 and CSS2.1 specifications, respectively.

1.1. 의존성

스펙 내 몇가지 기능은 CSS 고유 기능이며, 특정 제한사항 혹은 CSS 고유의 룰을 가집니다. 이 스펙에서는, 이러한 내용을 CSS 2.1의 조건대로 설명합니다. [CSS21]

Some features of this specification are specific to CSS, or have particular limitations or rules specific to CSS. In this specification, these have been described in terms of CSS2.1. [CSS21]

1.2. 용어

이 스펙문서 내에서 예제, 노트, 명시적으로 '이 섹션은 표준에 준하는 내용이 아닙니다'라 표기된 내용을 제외한 텍스트는 모두 표준에 준하는 내용입니다.

All of the text of this specification is normative except examples, notes, and sections explicitly marked as non-normative.

[CSS21]Definitions 섹션에서 더 많은 용어를 정의하고 있습니다. 문서 소스 코드 예제 및 XML [[XML10]] 혹은 HTML [[HTML40]] 문법 제공 등입니다.

Additional terminology is defined in the Definitions section of [CSS21]. Examples of document source code and fragments are given in XML [[XML10] or HTML [[HTML40]] syntax.

1.3. CSS2와 다른 점

이 섹션은 표준에 준하는 내용이 아닙니다.

This section is non-normative.

CSS2 셀렉터와 이 스펙문서에서 소개하는 셀렉터 간의 큰 차이점은 다음과 같습니다:

The main differences between the selectors in CSS2 and those in Selectors are:

2. 셀렉터

이 섹션은 다음 섹션을 소개하는 성격의 섹션으로 표준에 준하는 내용이 아닙니다.

This section is non-normative, as it merely summarizes the following sections.

셀렉터는 구조를 나타냅니다. 이 구조는 문서 트리 내 어떤 요소가 매치하는 지 결정하는 조건(CSS 룰에 의한 것)이나 그 구조에 대응하는 HTML 혹은 XML fragment로 이용합니다.

A Selector represents a structure. This structure can be used as a condition (e.g. in a CSS rule) that determines which elements a selector matches in the document tree, or as a flat description of the HTML or XML fragment corresponding to that structure.

셀렉터의 범위는 간단히 요소의 이름부터 문맥을 표현하기까지 넓게 확장합니다.

Selectors may range from simple element names to rich contextual representations.

다음 표에서 셀렉터 문법을 정리하고 있습니다.

The following table summarizes the Selector syntax:

패턴 의미 소개 섹션 CSS 레벨
* 모든 요소 전역 셀렉터 2
E E 타입 요소 타입 셀렉터 1
E[foo] "foo" 속성을 가진 E 요소 속성 셀렉터 2
E[foo="bar"] "foo" 속성값이 문자열 "bar"인 요소 속성 셀렉터 2
E[foo~="bar"] "foo" 속성값이 공백으로 구분된 값 목록에서, 하나 이상이 문자열 "bar"와 일치하는 요소 속성 셀렉터 2
E[foo^="bar"] "foo" 속성값이 문자열 "bar"로 시작하는 요소 속성 셀렉터 3
E[foo$="bar"] "foo" 속성값이 문자열 "bar"로 끝나는 요소 속성 셀렉터 3
E[foo*="bar"] "foo" 속성값에 문자열 "bar"를 포함하는 요소 속성 셀렉터 3
E[foo|="en"] "foo" 속성값이 하이픈으로 구분되는 리스트에서 (왼쪽을 기준으로) "en"으로 시작하는 요소 속성 셀렉터 2
E:root 문서의 루트인 E 요소 구조 의사 클래스 3
E:nth-child(n) 부모에서 n번째 자식인 E 요소 구조 의사 클래스 3
E:nth-last-child(n) 부모 내 마지막 요소부터 시작하여 n번째 자식인 E 요소 구조 의사 클래스 3
E:nth-of-type(n) 해당 타입의 n번째 형제인 E 요소 구조 의사 클래스 3
E:nth-last-of-type(n) 해당 타입의 마지막 요소부터 시작하여 n번째 형제인 E 요소 구조 의사 클래스 3
E:first-child 부모의 첫번째 자식 요소인 E 요소 구조 의사 클래스 2
E:last-child 부모의 마지막 자식 요소인 E 요소 구조 의사 클래스 3
E:first-of-type 해당 타입의 첫번째 형제요소인 E 요소 구조 의사 클래스 3
E:last-of-type 해당 타입의 마지막 형제요소인 E 요소 구조 의사 클래스 3
E:only-child 부모에서 유일한 자식인 E 요소 구조 의사 클래스 3
E:only-of-type 해당 타입에서 유일한 형제인 E 요소 구조 의사 클래스 3
E:empty (텍스트 노드를 포함한) 자식을 갖지 않는 E 요소 구조 의사 클래스 3
E:link
E:visited
아직 방문하지 않은(:link), 이미 방문한(:visited) 타겟 하이퍼링크 소스인 E 요소 링크 의사 클래스 1
E:active
E:hover
E:focus
유저가 액션을 취하는 동안 E 요소 유저 액션 의사 클래스 1 2
E:target URI 참조 타겟 E 요소 타겟 의사 클래스 3
E:lang(fr) (문서 언어가 어떻게 언어를 지정하는지에 따라) 언어 "fr"인 E 타입 요소 :lang() 의사 클래스 2
E:enabled
E:disabled
유저 인터페이스 요소인 E가 사용 가능 / 사용 불가능한 상태 UI 요소 상태 의사 클래스 3
E:checked 체크 되어있는 유저 인터페이스 요소 E (즉 라디오 버튼 혹은 체크박스) UI 요소 상태 의사 클래스 3
E::first-line E 요소의 첫번째 줄 ::first-line 의사 요소 1
E::first-letter E 요소의 첫번째 문자 ::first-letter 의사 요소 1
E::before E 요소 앞에 콘텐츠 생성 ::before 의사 요소 2
E::after E 요소 뒤에 콘텐츠 생성 ::after 의사 요소 2
E.warning "warning" 클래스를 가진 E 요소 (문서 언어가 어떻게 class를 지정하느냐에 따라 다름) 클래스 셀렉터 1
E#myid "myid" ID를 가진 E 요소. ID 셀렉터 1
E:not(s) 심플 셀렉터 s에 매치하지 않는 E 요소 부정 의사 클래스 3
E F E 요소의 자손 F 요소 자손 콤비네이터 1
E > F E 요소의 자식 F 요소 자식 콤비네이터 2
E + F E 요소 바로 다음에 이어지는 F 요소 인접 형제 콤비네이터 2
E ~ F E 요소 다음에 이어지는 F 요소 일반 형제 콤비네이터 3

각 셀렉터의 의미는 테이블의 "의미" 열 내 각 셀의 콘텐츠에 "~와 일치한다"라는 말을 붙여서 알 수 있습니다.

The meaning of each selector is derived from the table above by prepending "matches" to the contents of each cell in the "Meaning" column.

3. 대소문자 구별

모든 셀렉터 문법은 ASCII 범위(즉 [a-z][A-Z]와 동등) 내에서, 셀렉터의 제어 영역이 아닌 부분을 제외하면 대소문자를 구별하지 않습니다. 문서 언어에 의존하는 셀렉터 내에서 문서 언어의 요소명, 속성명, 속성값은 대소문자를 구별합니다. HTML을 예로 들면 요소명이 대소문자를 구별하지 않습니다. 하지만 XML에서는 대소문자를 구별합니다. 네임스페이스 접두사의 대소문자 구별은 [CSS3NAMESPACE]에서 정의합니다.

All Selectors syntax is case-insensitive within the ASCII range (i.e. [a-z] and [A-Z] are equivalent), except for parts that are not under the control of Selectors. The case sensitivity of document language element names, attribute names, and attribute values in selectors depends on the document language. For example, in HTML, element names are case-insensitive, but in XML, they are case-sensitive. Case sensitivity of namespace prefixes is defined in [CSS3NAMESPACE].

4. 셀렉터 문법

셀렉터콤비네이터로 구분된 한개 이상의 심플 셀렉터 시퀀스 체인입니다. 셀렉터 중 심플 셀렉터의 마지막 시퀀스인 경우 하나의 의사 요소를 넣는 것도 가능합니다.

A selector is a chain of one or more sequences of simple selectors separated by combinators. One pseudo-element may be appended to the last sequence of simple selectors in a selector.

심플 셀렉터 시퀀스콤비네이터로 구분되지 않은 심플 셀렉터 체인입니다. 이는 항상 타입 셀렉터전역 셀렉터로 시작합니다. 다른 타입 셀렉터나 전역 셀렉터를 시퀀스에서 허용하지 않습니다.

A sequence of simple selectors is a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.

심플 셀렉터타입 셀렉터, 전역 셀렉터, 속성 셀렉터, 클래스 셀렉터, ID 셀렉터, 혹은 의사 클래스 중 하나입니다.

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.

콤비네이터는: 공백 문자, "~보다 큰 기호" (U+003E, >), "덧셈 기호" (U+002B, +) 및 "물결표시" (U+007E, ~)입니다. 콤비네이터와 심플 셀렉터 사이에 공백 문자를 표시할 수 있습니다. 공백 문자에는 "space" (U+0020), "tab" (U+0009), "line feed" (U+000A), "carriage return" (U+000D), "form feed" (U+000C) 문자만 사용할 수 있습니다. "em-space" (U+2003)나 "ideographic space"(U+3000) 같은 다른 공백과 비슷한 문자는 공백 문자로 사용할 수 없습니다.

Combinators are: whitespace, "greater-than sign" (U+003E, >), "plus sign" (U+002B, +) and "tilde" (U+007E, ~). White space may appear between a combinator and the simple selectors around it. Only the characters "space" (U+0020), "tab" (U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form feed" (U+000C) can occur in whitespace. Other space-like characters, such as "em-space" (U+2003) and "ideographic space" (U+3000), are never part of whitespace.

셀렉터로 인해 나타나는 문서 내 요소는 셀렉터 대상이라 부릅니다. 하나의 심플 셀렉터 시퀀스로 구성된 셀렉터는 요구사항을 만족하는 어떤 요소라도 나타냅니다. 여기에 새로운 심플 셀렉터 시퀀스를 주어, 이를 콤비네이터로 엮은 케이스는, 매치하는 제한을 더합니다. 이렇게하면 셀렉터 대상은 항상 마지막 심플 셀렉터 시퀀스로 표현된 요수의 일부가 됩니다.

The elements of a document tree that are represented by a selector are the subjects of the selector. A selector consisting of a single sequence of simple selectors represents any element satisfying its requirements. Prepending another sequence of simple selectors and a combinator to a sequence imposes additional matching constraints, so the subjects of a selector are always a subset of the elements represented by the last sequence of simple selectors.

빈 셀렉터, 심플 셀렉터 시퀀스를 포함하지 않았거나 의사 요소가 없는 경우에 유효하지 않은 셀렉터가 됩니다.

An empty selector, containing no sequence of simple selectors and no pseudo-element, is an invalid selector.

셀렉터 내 문자는 CSS의 escaping rules와 동일하게 백슬래쉬와 함께 해석할 수 있습니다 [CSS21].

Characters in Selectors can be escaped with a backslash according to the same escaping rules as CSS. [CSS21].

몇가지 셀렉터는 네임스페이스 접두사를 지원합니다. 어떤 네임스페이스 접두사가 선언되었는지 알기 위한 메커니즘은 셀렉터를 이용하는 언어에 의해 정해져야만 합니다. 만약 언어가 네임스페이스 접두사 메커니즘을 정의하지 않은 경우, 접두사는 선언되지 않습니다. CSS에서, 네임스페이스 접두사는 @namespace 룰에 따라 선언합니다. [CSS3NAMESPACE]

Certain selectors support namespace prefixes. The mechanism by which namespace prefixes are declared should be specified by the language that uses Selectors. If the language does not specify a namespace prefix declaration mechanism, then no prefixes are declared. In CSS, namespace prefixes are declared with the @namespace rule. [CSS3NAMESPACE]

5. 셀렉터 그룹

콤마로 구분한 셀렉터의 목록은 리스트 안의 각 셀렉터로 인해 가져온 모든 요소의 연합을 나타냅니다. (콤마는 U+002C) 예를 들어, CSS에서 같은 선언을 공유하는 여러개의 셀렉터를 가질 때, 콤마로 구분된 목록으로 그룹핑 할 수 있습니다. 공백 문자는 콤마의 앞 뒤에 존재할 수 있습니다.

A comma-separated list of selectors represents the union of all elements selected by each of the individual selectors in the list. (A comma is U+002C.) For example, in CSS when several selectors share the same declarations, they may be grouped into a comma-separated list. White space may appear before and/or after the comma.

CSS 예제:

이 예제에서, 동일한 선언을 나타내는 세개의 규칙을 하나로 정리합니다.

h1 { font-family: sans-serif }
h2 { font-family: sans-serif }
h3 { font-family: sans-serif }

이는 아래와 같습니다.

h1, h2, h3 { font-family: sans-serif }

주의: 이 예제가 true인 이유는 예제의 셀렉터가 모두 유효한 셀렉터이기 때문입니다. 만약 이 예제 중 하나라도 유효하지 않다면, 모든 셀렉터 그룹은 유효하지 않다고 간주어집니다. 후자에서 그렇게 되면, 3개 헤딩 요소 모두 규칙이 유효하지 않다고 간주합니다. 전자에서는 그렇게 되더라도, 유효하지 않은 셀렉터를 가진 규칙만 유효하지 않다고 간주어지니다.

Warning: the equivalence is true in this example because all the selectors are valid selectors. If just one of these selectors were invalid, the entire group of selectors would be invalid. This would invalidate the rule for all three heading elements, whereas in the former case only one of the three individual heading rules would be invalidated.

유효하지 않은 CSS 예제:

h1 { font-family: sans-serif }
h2..foo { font-family: sans-serif }
h3 { font-family: sans-serif }

이는 아래와 동일하지 않습니다:

h1, h2..foo, h3 { font-family: sans-serif }

왜냐하면 위 셀렉터(h1, h2..foo, h3)는 모든 규칙을 유효하지 않다고 간주하여 모든 스타일 규칙을 적용하지 않기 때문입니다. (셀렉터를 그룹화하지 않았을 때, h2..foo 룰만 적용하지 않습니다.)

6. 심플 셀렉터

6.1. 타입 셀렉터

타입 셀렉터CSS qualified names 문법을 이용해 작성한 문서 언어 요소 타입 이름입니다. [CSS3NAMESPACE] 타입 셀렉터는 문서 트리 안에 있는 요소 타입의 인스턴스를 나타냅니다.

A type selector is the name of a document language element type written using the syntax of CSS qualified names [CSS3NAMESPACE]. A type selector represents an instance of the element type in the document tree.

예제:

아래 셀렉터는 문서 트리 안에 있는 h1 요소를 나타냅니다:

h1

6.1.1. 타입 셀렉터와 네임스페이스

타입 셀렉터는 옵션으로 네임스페이스 컴포넌트 사용을 허용합니다: 네임스페이스 컴포넌트는 사전에 선언된 네임스페이스 접두사와 요소명을 네임스페이스 구분자 "vertical bar" (U+007C, |)로 구분한 것을 나타냅니다. (XML에서 사용하는 네임스페이스 이용 예시는 [XML-NAMES]를 참고하시길 바랍니다)

Type selectors allow an optional namespace component: a namespace prefix that has been previously declared may be prepended to the element name separated by the namespace separator "vertical bar" (U+007C, |). (See, e.g., [XML-NAMES] for the use of namespaces in XML.)

셀렉터가 어떤 네임스페이스에도 속하지 않는 요소를 나타내기 위해, 네임스페이스 컴포넌트는 빈 (접두사와 구분자를 가지지 않는) 상태로 있어도 좋습니다

The namespace component may be left empty (no prefix before the namespace separator) to indicate that the selector is only to represent elements with no namespace.

셀렉터가 네임스페이스 접두사와 상관없이 (네임스페이스가 없는 요소도 포함하여) 요소를 선택 가능하도록 하기 위해, 네임스페이스 접두사에 별표를 사용할 수 있습니다.

An asterisk may be used for the namespace prefix, indicating that the selector represents elements in any namespace (including elements with no namespace).

네임스페이스 컴포넌트를 가지지 않는 (네임스페이스 구분자를 갖지 않는) 타입 셀렉터는 네임스페이스에 속하지 않는 요소("*|"와 동등)를 나타냅니다. 그러나, 네임스페이스 가지는 셀렉터 (CSS 스타일 시트 등) 기본 네임스페이스가 선언된 경우에는 이와 다릅니다. 기본 네임스페이스가 선언된 경우, 네임스페이스를 가지지 않는 타입 셀렉터는 기본 네임스페이스 내 요소만을 나타냅니다.

Element type selectors that have no namespace component (no namespace separator) represent elements without regard to the element's namespace (equivalent to "*|") unless a default namespace has been declared for namespaced selectors (e.g. in CSS, in the style sheet). If a default namespace has been declared, such selectors will represent only elements in the default namespace.

타입 셀렉터가 네임스페이스 접두사를 가지면서, 그 접두사에 대응하는 네임스페이스가 정의되어있지 안않다면 그 셀렉터는 유효하지 않은 셀렉터입니다.

A type selector containing a namespace prefix that has not been previously declared for namespaced selectors is an invalid selector.

네임스페이스를 이해하는 클라이언트에서, 타입 셀렉터의 요소명 부분 (네임스페이스 구분자 이후 부분)은 수식명local part에만 대응해 매치합니다.

In a namespace-aware client, the name part of element type selectors (the part after the namespace separator, if it is present) will only match against the local part of the element's qualified name.

이를 요약하면:

ns|E
네임스페이스 ns 안에 E라는 이름을 가진 요소
elements with name E in namespace ns
*|E
네임스페이스를 가지지 않는 것을 포함하여, 모든 네임스페이스 안의 E라는 이름을 가진 요소
elements with name E in any namespace, including those without a namespace
|E
네임스페이스를 가지지 않는 E라는 이름을 가진 요소
elements with name E without a namespace
E
셀렉터에 대한 기본 네임스페이스가 정의되어있지 않은 경우를 나타내며 이는 *|E와 동등합니다. 그 외의 경우에는 기본 네임스페이스를 ns로 하며 ns|E와 동일하게 취급합니다.

CSS 예제:

@namespace foo url(http://www.example.com);
 foo|h1 { color: blue }  /* first rule */
 foo|* { color: yellow } /* second rule */
 |h1 { color: red }      /* ...*/
 *|h1 { color: green }
 h1 { color: green }

(@namespace 규칙을 포함하지 않는) 첫번째 룰은 "http://www.example.com" 네임스페이스 내 h1 요소에만 매치할 것입니다. The first rule (not counting the @namespace at-rule) will match only h1 elements in the "http://www.example.com" namespace.

두번째 규칙은 "http://www.example.com" 네임스페이스 내 모든 요소에 매치할 것입니다. The second rule will match all elements in the "http://www.example.com" namespace.

세번째 규칙은 네임스페이스를 가지지 않는 h1 요소에만 매치할 것입니다. The third rule will match only h1 elements with no namespace.

네번째 규칙은 (네임스페이스를 가지지 않는 것을 포함한) 어떤 네임스페이스 내의 h1 요소에도 매치할 것입니다. The fourth rule will match h1 elements in any namespace (including those without any namespace).

마지막 규칙은 기본 네임스페이스를 정의하지 않았기 때문에 네번째 규칙과 동일합니다. The last rule is equivalent to the fourth rule because no default namespace has been defined.

6.2. 전역 셀렉터

로컬명으로 별표(* U+002A)와 함께 CSS qualified name [CSS3NAMESPACE]으로써 작성된 전역셀렉터는, 모든 요소 타입의 수식명을 나타냅니다. 이는 기본 네임스페이스가 셀렉터에 대해 지정되어있는 경우를 제외하고, (네임스페이스가 없는 것을 포함한) 모든 네임스페이스 내 문서 트리 안 모든 개별 요소를 나타냅니다. 만약 기본 네임스페이스가 정의되어 있다면, 전역 셀렉터와 네임스페이스를 참고하시길 바랍니다.

The universal selector, written as a CSS qualified name [CSS3NAMESPACE] with an asterisk (* U+002A) as the local name, represents the qualified name of any element type. It represents any single element in the document tree in any namespace (including those without a namespace) if no default namespace has been specified for selectors. If a default namespace has been specified, see Universal selector and Namespaces below.

전역셀렉터 *이, (즉 네임스페이스 접두사를 갖지 않는) 심플 셀렉터 시퀀스 내 컴포넌트 하나가 아니며, 바로 뒤에 의사 요소가 존재하지 않는 경우, 그 *을 생략하여 전역 셀렉터의 존재를 나타내도 무관합니다.

If a universal selector represented by * (i.e. without a namespace prefix) is not the only component of a sequence of simple selectors selectors or is immediately followed by a pseudo-element, then the * may be omitted and the universal selector's presence implied.

예제:

노트:혼란을 피하기 위해 *을 생략하지 않는걸 권장합니다. 예를 들어 div :first-childdiv:first-child를 생각해보면 이해가 빠릅니다. 여기서 div *:first-child가 더 가독성이 좋을 것입니다. Note: it is recommended that the * not be omitted, because it decreases the potential confusion between, for example, div :first-child and div:first-child. Here, div *:first-child is more readable.

6.2.1. 전역 셀렉터와 네임스페이스

전역 셀렉터는 옵션적으로 네임스페이스 컴포넌트 사용을 허용합니다. 이는 다음과 같이 사용합니다. The universal selector allows an optional namespace component. It is used as follows:

ns|*
네임스페이스 ns 내 모든 요소
all elements in namespace ns
*|*
모든 요소
all elements
|*
네임스페이스를 가지지 않는 모든 요소
all elements without a namespace
*
기본 네임스페이스가 선언되어있지 않은 경우, 이는 *|*과 동일합니다. 그 외의 경우, ns는 기본 네임스페이스로 간주하여 ns|*와 동일합니다.
if no default namespace has been specified, this is equivalent to *|*. Otherwise it is equivalent to ns|* where ns is the default namespace.

선언되지 않은 네임 스페이스를 포함한 전역 셀렉터는 유효하지 않은 셀렉터 입니다.

A universal selector containing a namespace prefix that has not been previously declared is an invalid selector.

6.3. 속성 셀렉터

셀렉터는 요소 속성 표현도 가능합니다. 셀렉터를 요소에 매치하는 표현식으로 사용할 떄, 속성 셀렉터는 그 셀렉터에 의해 표현하는 속성에 매치하는 속성을 가진 요소에 매치합니다.

Selectors allow the representation of an element's attributes. When a selector is used as an expression to match against an element, attribute selectors must be considered to match an element if that element has an attribute that matches the attribute represented by the attribute selector.

6.3.1. 속성 의존 셀렉터와 속성값 셀렉터

CSS2는 네 속성 셀렉터를 소개합니다:

[att]
Represents an element with the att 속성을 가진 요소를 나타내며, 속성값은 무관합니다.
Represents an element with the att attribute, whatever the value of the attribute.
[att=val]
att 속성을 가지며 속성의 값이 "val"와 일치하는 요소를 나타냅니다.
Represents an element with the att attribute whose value is exactly "val".
[att~=val]
att 속성을 가지며 속성의 값이 공백 문자로 구분된 문자의 목록일 때, 목록 중 하나가 "val"와 일치하는 요소를 나타냅니다. 만약 "val"이 빈 문자열이라면, 그 무엇도 표현하지 않습니다.
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.
[att|=val]
att 속성을 가지며, 그 값이 "val" 혹은, "val"에 이어 "-"(U+002D) 문자열로 이어지는 문자열로 시작하는 요소를 나타냅니다. 이 셀렉터는 특히, BCP 47 ([BCP47]) 혹은 그 개정판에서 정의하는 언어의 서브코드 매칭(HTML a 요소의 hreflang 속성 등)을 할 수 있게 이루어져 있습니다. lang (혹은 xml:lang)속성에 의한 언어 서브코드 매칭은 the :lang 의사 클래스를 확인하시길 바랍니다.
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D). This is primarily intended to allow language subcode matches (e.g., the hreflang attribute on the a element in HTML) as described in BCP 47 ([BCP47]) or its successor. For lang (or xml:lang) language subcode matching, please see the :lang pseudo-class.

속성명은 반드시 CSS 식별자문자열이여야 합니다. [CSS21] 셀렉터 내의 속성명과 값의 대소문자 구별에 관해서는 문서 언어에 의존합니다.

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

예제:

아래 예제는 title 속성을 갖고 있는 h1 요소를 나타내며, 값은 상관 없습니다: The following attribute selector represents an h1 element that carries the title attribute, whatever its value:

h1[title]

아래 예제에서, 셀렉터는 class 속성을 가지고 그 값이 정확히 "example"과 일치하는 span 요소를 나타냅니다. In the following example, the selector represents a span element whose class attribute has exactly the value "example":

span[class="example"]

하나의 요소의 여러가지 속성을 나타내거나, 같은 속성에 다른 조건을 주기 위해 다중 속성 셀렉터를 사용할 수 있습니다. 다음 예제에서 셀렉터는 hello 속성을 가지며 그 값이 "Cleveland"이고, goodbye 속성을 가지며 그 값이 "Columbus"인 span 요소를 나타냅니다. Multiple attribute selectors can be used to represent several attributes of an element, or several conditions on the same attribute. Here, the selector represents a span element whose hello attribute has exactly the value "Cleveland" and whose goodbye attribute has exactly the value "Columbus":

span[hello="Cleveland"][goodbye="Columbus"]

다음 CSS 규칙은 "="과 "~=" 사이의 차이점에 대해 소개합니다. 첫번째 셀렉터는 a 요소의 rel 속성 값이 "copyright copyleft copyeditor"인 경우 매치할 것이며, 두번째 셀렉터는 a 요소의 href 속성 값이 정확히 "http://www.w3.org/"인 경우 매치할 것입니다. The following CSS rules illustrate the differences between "=" and "~=". The first selector would match, for example, an a element with the value "copyright copyleft copyeditor" on a rel attribute. The second selector would only match an a element with an href attribute having the exact value "http://www.w3.org/".

a[rel~="copyright"] { ... }
a[href="http://www.w3.org/"] { ... }

다음 셀렉터는 a 요소의 hreflang 속성이 정확히 "fr"인 경우를 나타냅니다. The following selector represents an a element whose hreflang attribute is exactly "fr".

a[hreflang=fr]

다음 셀렉터는 a 요소의 hreflang 속성이 "en"으로 시작하는 것을 나타내며, 이는 "en", "en-US", "en-scouse"를 포함합니다. The following selector represents an a element for which the value of the hreflang attribute begins with "en", including "en", "en-US", and "en-scouse":

a[hreflang|="en"]

다음 셀렉터는 character 속성에 두개의 다른 값 중 하나를 가질 수 있는 DIALOGUE 요소를 나타냅니다. The following selectors represent a DIALOGUE element whenever it has one of two different values for an attribute character:

DIALOGUE[character=romeo]
DIALOGUE[character=juliet]

6.3.2. 부분 매칭 속성 셀렉터

속성 값에 부분 매칭하기 위한 세 추가 셀렉터를 제공합니다.

Three additional attribute selectors are provided for matching substrings in the value of an attribute:

[att^=val]
att 속성을 가지며 해당 속성 값이 "val" 접두사로 시작하는 요소를 나타냅니다. 만약 "val"이 빈 문자열이라면 셀렉터는 아무 것도 나타내지 않습니다.
Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.
[att$=val]
att 속성을 가지며 해당 속성 값이 "val" 접미사로 끝나는 요소를 나타냅니다. 만약 "val"이 빈 문자열이라면 셀렉터는 아무 것도 나타내지 않습니다.
Represents an element with the att attribute whose value ends with the suffix "val". If "val" is the empty string then the selector does not represent anything.
[att*=val]
att 속성을 가지며 해당 속성 값이 "val" 부분 문자열을 최소 1개 이상 포함하는 요소를 나타냅니다. 만약 "val"이 빈 문자열이라면 셀렉터는 아무 것도 나타내지 않습니다.
Represents an element with the att attribute whose value contains at least one instance of the substring "val". If "val" is the empty string then the selector does not represent anything.

속성명은 반드시 CSS 식별자문자열이여야 합니다. [CSS21] 셀렉터 내의 속성명과 값의 대소문자 구별에 관해서는 문서 언어에 의존합니다.

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

예제:

아래 셀렉터는 image를 참조하는 HTML object 객체를 나타냅니다. The following selector represents an HTML object, referencing an image:

object[type^="image/"]

아래 셀렉터는 href 속성 값이 ".html"로 끝나는 HTML 앵커 a 요소를 나타냅니다. The following selector represents an HTML anchor a with an href attribute whose value ends with ".html".

a[href$=".html"]

아래 셀렉터는 title 속성의 값에 "hello" 부분 문자열을 포함하는 HTML 문장(p요소)을 나타냅니다. The following selector represents an HTML paragraph with a title attribute whose value contains the substring "hello"

p[title*="hello"]

6.3.3. 속성 셀렉터와 네임스페이스

셀렉터 내의 속성명은 CSS 수식명으로써 제공됩니다: 네임스페이스가 사전에 선언된 경우, 속성명 앞에 접두사를 네임스페이스 구분자"vertical bar" (|)로 구분해 표현하는 것이 가능합니다. XML 내 네임스페이스 권고안과 스펙을 맞추기 위해, 기본 네임스페이스는 속성에 사용하지 않습니다. 즉, 네임스페이스 컴포넌트를 가지지 않는 속성 셀렉터는, 네임스페이스에 속하지 않는 속성만 사용합니다 (이는 "|attr"과 동일합니다. 또 이 속성은 "per-element-type namespace partition"에 있다고 간주합니다). 셀렉터가 네임스페이스에 상관없이 모든 속성에 매치한다는 걸 나타내고 싶을 때, 별표를 네임스페이스 접두사로 사용할 수 있습니다.

The attribute name in an attribute selector is given as a CSS qualified name: a namespace prefix that has been previously declared may be prepended to the attribute name separated by the namespace separator "vertical bar" (|). In keeping with the Namespaces in the XML recommendation, default namespaces do not apply to attributes, therefore attribute selectors without a namespace component apply only to attributes that have no namespace (equivalent to "|attr"; these attributes are said to be in the "per-element-type namespace partition"). An asterisk may be used for the namespace prefix indicating that the selector is to match all attribute names without regard to the attribute's namespace.

속성 셀렉터 내의 속성명에 네임스페이스 접두사르 가지면서, 그 접두사에 대한 선언을 하지 않은 경우, 이는 유효하지 않은 셀렉터입니다.

An attribute selector with an attribute name containing a namespace prefix that has not been previously declared is an invalid selector.

CSS 예제:

@namespace foo "http://www.example.com";
[foo|att=val] { color: blue }
[*|att] { color: yellow }
[|att] { color: green }
[att] { color: green }

첫번째 규칙은 "http://www.example.com" 네임스페이스 안에서 att 속성을 가지며, 값이 "val"인 요소를 나타냅니다. The first rule will match only elements with the attribute att in the "http://www.example.com" namespace with the value "val".

두번째 규칙은 (네임스페이스가 없는 걸 포함하여) 네임스페이스에 상관 없이 att 속성을 가지는 요소를 나타냅니다. The second rule will match only elements with the attribute att regardless of the namespace of the attribute (including no namespace).

마지막 두 규칙은 동일하며, 네임스페이스에 속하지 않는 att 속성을 가진 요소를 나타냅니다. The last two rules are equivalent and will match only elements with the attribute att where the attribute is not in a namespace.

6.3.4. DTD 내 기본 속성값

속성 셀렉터는 문서 트리 내의 속성 값을 나타냅니다. 문서 트리가 어떻게 구축되어 있는 지는 셀렉터 스펙의 범위 밖입니다. 몇몇 문서 포맷은 DTD 혹은 그 외의 방법으로 속성의 기본값을 정의 가능하지만, 속성 셀렉터를 이용해 선택 가능한 건 기본 값이 문서 트리에 나타날 때 뿐입니다. 이를 위해, 문서 트리에 기본 값이 있던 없던 동작 가능하도록 셀렉터를 설계하고 있습니다.

Attribute selectors represent attribute values in the document tree. How that document tree is constructed is outside the scope of Selectors. In some document formats default attribute values can be defined in a DTD or elsewhere, but these can only be selected by attribute selectors if they appear in the document tree. Selectors should be designed so that they work whether or not the default values are included in the document tree.

예를 들어, XML UA는 필수는 아니지만 DTD의 "외부 서브셋"을 읽어올 수 있습니다. 그러나 문서 "내부 서브셋" 안의 어떤 속성 기본 값을 찾는 데는 DTD가 필수입니다. (서브셋 정의에 관련된 내용은 [XML10] 참고) DTD의 외부 서브셋에 의해 정의된 속성의 기본 값은, UA에 따라 문서 트리에 나타나거나, 나타나지 않거나 할 것입니다.

For example, a XML UA may, but is not required to read an "external subset" of the DTD but is required to look for default attribute values in the document's "internal subset." (See, e.g., [XML10] for definitions of these subsets.) Depending on the UA, a default attribute value defined in the external subset of the DTD might or might not appear in the document tree.

XML 네임스페이스를 이해하는 UA는 필수는 아니지만, 네임스페이스를 이용해서 속성의 기본값이 문서 트리 안에 나타나고 있는 듯 표현하는 게 가능합니다. (예를 들어, XHTML UA는 XHTML DTD의 정의를 이용하지 않아도 됩니다. 자세한 내용은 Namespaces in XML 1.0을 참조하시길 바랍니다. [XML-NAMES]

A UA that recognizes an XML namespace may, but is not required to use its knowledge of that namespace to treat default attribute values as if they were present in the document. (For example, an XHTML UA is not required to use its built-in knowledge of the XHTML DTD. See, e.g., [XML-NAMES] for details on namespaces in XML 1.0.)

노트: 일반적으로, 구현체는 외부 서브셋을 무시합니다. 이는 XML 스펙에 있어 유효성 검사를 진행하지 않은 서브셋의 동작과 일치합니다.

Note: Typically, implementations choose to ignore external subsets. This corresponds to the behaviour of non-validating processors as defined by the XML specification.

예제:

radix 속성의 기본 값이 "demical"인 요소 EXAMPLE이 있다고 했을 때, DTD는 아래와 같이 구성합니다. Consider an element EXAMPLE with an attribute radix that has a default value of "decimal". The DTD fragment might be

<!ATTLIST EXAMPLE radix (decimal,octal) "decimal">

여기서 스타일 시트가 아래와 같은 규칙을 가진다고 하였을 때 If the style sheet contains the rules

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

첫번째 규칙은 radix 속성이 기본으로 설정되어있는 요소, 즉 속성이 명시적으로 지정되어있지 않은 것에 매치하지 않을 가능성이 있습니다. 모든 가능성에 대비하기 위해, 기본 값에 대한 속성 셀렉터는 제거하지 않으면 안됩니다. the first rule might not match elements whose radix attribute is set by default, i.e. not set explicitly. To catch all cases, the attribute selector for the default value must be dropped:

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

EXAMPLE[radix=octal]는 타입 셀렉터보다 상세하기 때문에, radix 속성값이 "octal"인 요소에서는 2번째 규칙에 있는 스타일 선언이 1번째 스타일 선언을 덮어쓸 것입니다. 디폴트 상태에서 적용하는 모든 속성 선언은, 그 외의 상태에 대해 적용하는 스타일 룰에 덮어쓰여지는 점에 주의하시길 바랍니다. Here, because the selector EXAMPLE[radix=octal] is more specific than the type selector alone, the style declarations in the second rule will override those in the first for elements that have a radix attribute value of "octal". Care has to be taken that all property declarations that are to apply only to the default case are overridden in the non-default cases' style rules.

6.4. 클래스 셀렉터

HTML에서, 작성자는 ~= 기호를 대신해서 "페리오드" 표기법 (또한 "마침표"로 알려져있는, U+002E, .)을 사용할 수 있습니다. HTML을 가져올 때 div.valuediv[class~=value)는 같은 의미입니다. 속성 값은 반드시 마침표 (.) 뒤에 표기해야 합니다.

Working with HTML, authors may use the "period" notation (also known as "full stop", U+002E, .) as an alternative to the ~= notation when representing the class attribute. Thus, for HTML, div.value and div[class~=value] have the same meaning. The attribute value must immediately follow the full stop (.).

네임스페이스에 있어서 속성이 "class" 속성을 결정하는, 네임스페이스 고유의 처리를 UA가 가지고 있는 경우, UA는 "마침표" 기호를 그 XML 문서에서도 사용할 수 있습니다. 메임스페이스 고유의 처리를 예로 들자면 스펙 문장에서 정의되어 있습니다. (예: SVG 1.0 [SVG11]SVG class 속성을 정의하며, UA가 어떻게 해석해야하는 지 설명하고 있습니다. MathML 1.01 [MATHML]도 마찬가지로 MathML class 속성을 정의하고 있습니다)

UAs may apply selectors using the period (.) notation in XML documents if the UA has namespace-specific knowledge that allows it to determine which attribute is the "class" attribute for the respective namespace. One such example of namespace-specific knowledge is the prose in the specification for a particular namespace (e.g. SVG 1.0 [SVG11] describes the SVG class attribute and how a UA should interpret it, and similarly MathML 1.01 [MATHML] describes the MathML class attribute.)

CSS 예제:

class~="pastoral"인 모든 요소에 대해 스타일을 적용할 때 아래와 같이 작성합니다. We can assign style information to all elements with class~="pastoral" as follows:

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

혹은 단순하게 or just

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

class~="pastoral"인 H1 요소에 스타일을 적용할 때 아래와 같이 작성합니다. The following assigns style only to H1 elements with class~="pastoral":

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

이 규칙을 적용했을 때, 첫번째 H1 인스턴스는 녹색이 아니지만, 두번째 H1은 녹색입니다. Given these rules, the first H1 instance below would not have green text, while the second would:

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

아래 규칙은 P 요소 중에서, class 속성값에 pastoralmaring을 포함한 것을 매치합니다. 이 때 class 속성값은 공백 문자로 구분된 값의 리스트입니다. The following rule matches any P element whose class attribute has been assigned a list of whitespace-separated values that includes both pastoral and marine:

p.pastoral.marine { color: green }

위 규칙은 class="pastoral blue aqua marine"에 매치하지만, class="pastoral blue"에는 매치하지 않습니다. This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".

노트: CSS에 "class" 속성을 주는 게 큰 파워를 가지기 때문에, 작성자는 (HTML의 DIVSPAN같은) 기본 표현을 거의 가지지 않은 요소에 "class" 속성으로 스타일 정보를 주어 자신의 "문서 언어"를 설계할 수 있습니다. 그러나 작성자는 문서 언어의 구조화 요소 의미와 의도를 이해하기 위해 이러한 사용을 피하길 바라며, 문서 요소는 작성자가 정의한 클래스를 이해하지 못할 것입니다.

Note: Because CSS gives considerable power to the "class" attribute, 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.

노트: 요소가 복수의 class 속성을 가지고 있는 경우, 각각의 값은 클래스를 검색하기 전에 공백 문자로 결합되어있어야 합니다. 그러나 현 시점에서 CSS 워킹 그룹은 그런 사태를 상정한 상황을 인식하고 있지 않기 때문에, 이 동작은 표준에 준하는 내용은 아닙니다.

Note: If an element has multiple class attributes, their values must be concatenated with spaces between the values before searching for the class. As of this time the working group is not aware of any manner in which this situation can be reached, however, so this behavior is explicitly non-normative in this specification.

6.5. ID 셀렉터

문서 언어는 ID 타입으로 선언된 속성을 가질 수 있습니다. ID 타입 속성이 특별한 이유는 결합된 문서에서 속성이 주어지는 요소의 타입을 묻지 않고, 같은 값을 가진 속성이 두개 존재할 수 없기 때문입니다. 문서 언어가 무엇이던, ID 타입 속성은 요소를 유니크하게 만들 때 사용합니다. HTML 언어에 있어 ID 타입 속성은 모든 "id"라는 이름을 가집니다. XML 언어에서는 ID 타입 속성이 다른 이름을 가질 수 있지만, 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 in a conformant document, regardless of the type of the elements that carry them; whatever the document language, an ID typed 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 타입 속성은 문서 트리 내 하나의 요소 인스턴스 식별자로 주어집니다. ID 셀렉터는 "해쉬" (U+0023, #) 직후에 ID 타입 속성 값을 적어 표기합니다. 값은 CSS식별자여야 합니다. ID 셀렉터는 셀렉터 내 식별자에 매치하는 식별자를 가진 요소를 나타냅니다.

An ID-typed attribute of a document language allows authors to assign an identifier to one element instance in the document tree. An ID selector contains a "number sign" (U+0023, #) immediately followed by the ID value, which must be an CSS identifiers. An ID selector represents an element instance that has an identifier that matches the identifier in the ID selector.

셀렉터 스펙은 UA가 어떻게 요소 내의 ID 타입 속성을 아는지 정의하지 않습니다. UA가 문서의 DTD를 읽고, ID 타입 속성의 정보를 UA에 결합하여, 유저에게 물어보는 정도로 예상됩니다.

Selectors does not specify how a UA knows the ID-typed attribute of an element. The UA may, e.g., read a document's DTD, have the information hard-coded or ask the user.

예제:

다음 ID 셀렉터는 ID 타입 속성 값으로 "chapter1"을 가지는 h1 요소를 나타냅니다. The following ID selector represents an h1 element whose ID-typed attribute has the value "chapter1":

h1#chapter1

다음 ID 셀렉터는 ID 타입 속성 값으로 "chapter1"을 가지는 모든 요소를 나타냅니다. The following ID selector represents any element whose ID-typed attribute has the value "chapter1":

#chapter1

다음 셀렉터는 ID 타입 속성 값으로 "z98y"를 가지는 모든 요소를 나타냅니다. The following selector represents any element whose ID-typed attribute has the value "z98y".

*#z98y

노트: XML 1.0 [XML10]에서, 어떤 속성이 요소의 ID인지 나타내는 정보는 DTD 혹은 스키마 언어에 있다고 간주어집니다. UA는 XML을 해석할 때 항상 DTD를 읽어들이는 게 아니므로, 요소의 ID가 무엇인지 모를 가능성도 있습니다. (그러나 UA가 네임스페이스 고유 처리를 가지고, 그 네임스페이스에서 어떤 속성이 ID 속성인지 알릴 가능성도 있습니다) 그 UA가 요소의 ID를 모른다면, 스타일시트의 작성자가 알고있는, 혹은 추측 가능한 경우, ID 셀렉터가 아닌 속성 셀렉터를 사용해야 합니다. 즉 #p371 대신에 [name=p371]를 사용합니다.

Note: In XML 1.0 [XML10], the information about which attribute contains an element's IDs is contained in a DTD or a schema. When parsing XML, UAs do not always read the DTD, and thus may not know what the ID of an element is (though a UA may have namespace-specific knowledge that allows it to determine which attribute is the ID attribute for that namespace). If a style sheet author knows or suspects that a UA may not know what the ID of an element is, he should use normal attribute selectors instead: [name=p371] instead of #p371.

만약 요소가 여러개의 ID 속성을 가지고 있는 경우 모든 값을 그 요소의 ID로 취급하여, ID 셀렉터 처리대상으로 인식해야 합니다. 이는 xml:id, DOM3 Core, XML DTD, 네임스페이스 고유 처리가 엮일 때 발생할 가능성이 있습니다.

If an element has multiple ID attributes, all of them must be treated as IDs for that element for the purposes of the ID selector. Such a situation could be reached using mixtures of xml:id, DOM3 Core, XML DTDs, and namespace-specific knowledge.

6.6. 의사 클래스

의사 클래스는 문서 트리 범위에 포함하지 않는 정보나, 심플 셀렉터로는 표현 불가능한 것을 선택 가능하도록 도입한 컨셉입니다.

The pseudo-class concept is introduced to permit selection based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors.

의사 클래스는 항상 "콜론" (:)으로 시작하며, 그 이후에 의사 클래스 명을 입력해 표시하며, 선택적으로 괄호를 이용해 값을 가지는 것도 있습니다.

A pseudo-class always consists of a "colon" (:) followed by the name of the pseudo-class and optionally by a value between parentheses.

의사 클래스는 셀렉터가 포함하는 모든 심플 셀렉터 시퀀스를 허용합니다. 의사 클래스는 의사 클래스는 타입 셀렉터나 (생략 가능한)전역 셀렉터를 읽어들인 뒤 심플 셀렉터 시퀀스 내 모든 곳에 허용합니다. 의사 클래스 이름은 대소문자를 구분하지 않습니다. 몇몇 의사 클래스는 상호 배타적이며, 같은 요소에 동시에 사용하는 건 가능합니다. 의사 클래스는 동적일 수 있으며, 유저와 문서간 인터렉션에 반응해서 의사 클래스가 잡히거나 사라질 수 있습니다.

Pseudo-classes are allowed in all sequences of simple selectors contained in a selector. Pseudo-classes are allowed anywhere in sequences of simple selectors, after the leading type selector or universal selector (possibly omitted). Pseudo-class names are case-insensitive. Some pseudo-classes are mutually exclusive, while others can be applied simultaneously to the same element. 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.

6.6.1. 동적 의사 클래스

동적 의사 클래스는 요소명, 속성, 내용을 제외한 문서 트리에서 추론할 수 없는 성질에서 요소를 분류하는 것입니다.

Dynamic pseudo-classes classify elements on characteristics other than their name, attributes, or content, in principle characteristics that cannot be deduced from the document tree.

동적 의사 클래스는 문서 트리나 문서 소스에는 나타나지 않습니다.

Dynamic pseudo-classes do not appear in the document source or document tree.

보통 유저 에이전트는 이미 방문한 링크와 그렇지 않은 링크를 구분해서 보여줍니다. 셀렉터에서는 이 구분을 위한 :link:visited 의사 클래스를 제공합니다.

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

일정 시간이 지나면, UA는 이미 방문한 링크를 (방문하지 않은 링크인) ‘:link’ 상태로 변환합니다.

After some amount of time, user agents may choose to return a visited link to the (unvisited) ‘:link’ state.

이 두 상태는 상호 배타적입니다.

The two states are mutually exclusive.

예제:

아래 셀렉터는 external 클래스를 가지며 이미 방문한 링크를 나타냅니다. The following selector represents links carrying class external and already visited:

a.external:visited

노트: 스타일시트 작성자가 :link, :visited 의사 클래스를 악용하여, 유저가 어떤 사이트에 접속했는지 유저의 허락 없이 확인할 수 있습니다.

Note: It is possible for style sheet authors to abuse the :link and :visited pseudo-classes to determine which sites a user has visited without the user's consent.

따라서 UA는 모든 링크를 방문하지 않음으로 인식하거나, 각각의 링크를 표시할 때 유저의 프라이버시를 배려한 방법을 구현하는 등의 조치를 취할 수 있습니다.

UAs may therefore treat all links as unvisited links, or implement other measures to preserve the user's privacy while rendering visited and unvisited links differently.

6.6.1.2. 유저 액션 의사 클래스 :hover, :active, :focus

인터렉티브 유저 에이전트는 유저의 행동에 반응하여 렌더링을 변경합니다. 셀렉터는 유저의 행동에 따라서 요소를 선택하는 3개의 의사 클래스를 제공합니다.

Interactive user agents sometimes change the rendering in response to user actions. Selectors provides three pseudo-classes for the selection of an element the user is acting on.

문서 언어나 구현체의 한계에 따라, :active:focus가 주어졌으나, 가져 올 수 있는 요소와 그렇지 않은 요소가 있을 수 있습니다.

There may be document language or implementation specific limits on which elements can become :active or acquire :focus.

이 의사 클래스는 상호 배타적이지 않습니다. 요소는 동일한 시간에 여러개의 의사 클래스에 매치할 수 있습니다.

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

셀렉터의 부모에 ‘:active’나 ‘:hover’ 상태를 지원하는 지에 대해서 이 스펙에서는 정의하지 않습니다.

Selectors doesn't define if the parent of an element that is ‘:active’ or ‘:hover’ is also in that state.

노트: 그 요소의 자식이 포인팅 디바이스에서 지정되었으며 요소 자신이 ‘:hover’ 상태가 되는 경우, ‘:hover’가 포인팅 디바이스 밑이 아닌 요소에 적용되는 것도 고려해야합니다.

Note: If the ‘:hover’ state applies to an element because its child is designated by a pointing device, then it's possible for ‘:hover’ to apply to an element that is not underneath the pointing device.

예제:

a:link    /* unvisited links */
a:visited /* visited links */
a:hover   /* user hovers */
a:active  /* active links */

동적 의사 클래스에 결합하는 예제입니다: An example of combining dynamic pseudo-classes:

a:focus
a:focus:hover

마지막 셀렉터는 의사 클래스 :focus와 의사 클래스 :hover 상태인 a 요소와 매치합니다. The last selector matches a elements that are in the pseudo-class :focus and in the pseudo-class :hover.

노트: 요소는 ‘:visited’와 ‘:active’ (혹은 ‘:link’ 와 ‘:active’) 양쪽을 동시에 사용 가능합니다.

Note: An element can be both ‘:visited’ and ‘:active’ (or ‘:link’ and ‘:active’).

6.6.2. 타겟 의사 클래스 :target

"해쉬" (#) 기호와 뒤에 앵커 식별자를 가진 URI 같은 몇몇 URI는 리소스의 위치를 참조합니다. (부분 식별자라 부릅니다)

Some URIs refer to a location within a resource. This kind of URI ends with a "number sign" (#) followed by an anchor identifier (called the fragment identifier).

부분 식별자가 붙은 URI는 문서 내 특정 요소에 링크하며, 이를 타겟 요소라고 부릅니다. 아래는 HTML 문서 내에서 section_2라 이름붙여진 요소를 참조하는 URI입니다.

URIs with fragment identifiers link to a certain element within the document, known as the target element. For instance, here is a URI pointing to an anchor named section_2 in an HTML document:

http://example.com/html/top.html#section_2

타겟 요소는 :target 의사 클래스를 이용해 나타낼 수 있습니다. 만약 문서의 URI가 부분 식별자를 가지지 않는다면, 해당 문서에 타겟 요소는 존재하지 않습니다.

A target element can be represented by the :target pseudo-class. If the document's URI has no fragment identifier, then the document has no target element.

예제:

p.note:target

이 셀렉터는 참조 URI의 타겟 요소이며 note라는 클래스를 가진 p요소를 의미합니다. This selector represents a p element of class note that is the target element of the referring URI.

CSS 예제:

여기, :target 의사 클래스를 사용하여 타겟 요소의 색상을 붉게 하고 그 요소의 앞에 이미지를 둘 때 사용하는 예제입니다: Here, the :target pseudo-class is used to make the target element red and place an image before it, if there is one:

*:target { color : red }
*:target::before { content : url(target.png) }

6.6.3. 언어 의사 클래스 :lang

문서 언어가 요소가 어떤 인간 언어로 작성되어있는 지 결정하는 수단을 정의하는 경우, 그 언어 정보로 요소를 선택하는 게 가능합니다. 예를 들어 HTML에서 [HTML401], lang 속성이나 meta 요소, 혹은 프로토콜 (HTTP 헤더 등) 등 몇가지 방법으로 문서의 언어정보를 취득할 수 있습니다. XML에서는 xml:lang 속성을 사용하며, 언어 정보를 판별하는 언어 고유의 구조가 있을 가능성이 있습니다.

If the document language specifies how the human language of an element is determined, it is possible to write selectors that represent an element based on its language. For example, in HTML [HTML401], the language is determined by a combination of the lang attribute and possibly information from the meta elements or 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.

의사 클래스 :lang(C)은 C라는 언어를 가진 요소를 나타냅니다. 요소가 셀렉터에 의해 표현되어지고 있는 지는, 요소의 언어값(필요에 의해 BCP 47 문법을 통해 정규화 됨)이 식별자 C와 동일하거나 식별자 C로 시작해서 바로 뒤에 "-"(U+002D)가 있는 지를 기본으로 합니다. 요소의 언어값과 식별자 C간 매칭은 ASCII 범위 내에서 대소문자를 구분하지 않습니다. 식별자 C는 유효한 언어 이름이여야 합니다.

The pseudo-class :lang(C) represents an element that is in language C. Whether an element is represented by a :lang() selector is based solely on the element's language value (normalized to BCP 47 syntax if necessary) being equal to the identifier C, or beginning with the identifier C immediately followed by "-" (U+002D). The matching of C against the element's language value is performed case-insensitively. The identifier C does not have to be a valid language name.

C는 유효한 CSS 식별자 [CSS21]여야 하며 공백이어선 안됩니다. (그 외의 경우 모두 유효하지 않습니다)

C must be a valid CSS identifier [CSS21] and must not be empty. (Otherwise, the selector is invalid.)

노트: 문서나 프로토콜이 언어 정보를 나타낼 때, 값은 BCP 47[BCP47](혹은 개정판)의 언어 코드를 이용하는 걸 권장합니다. 또, XML 기반 문서에서 "xml:lang" 속성을 사용할 경우, 그 값에 BCP 47 코드를 사용하게 됩니다. [XML10] "FAQ: 두 글자 혹은 세 글자 언어 코드"를 참고하시길 바랍니다.

Note: It is recommended that documents and protocols indicate language using codes from BCP 47 [BCP47] or its successor, and by means of "xml:lang" attributes in the case of XML-based documents [XML10]. See "FAQ: Two-letter or three-letter language codes."

예제:

아래 두 셀렉터는 벨기에식 프랑스어나 독일어로 시작하는 HTML 문서를 나타냅니다. 그 다음 두 셀렉터는 벨기에식 프랑스어나 독일어라 명시된 임의의 요소의 자식 q 인용구를 나타냅니다. The two following selectors represent an HTML document that is in Belgian French or German. The two next selectors represent q quotations in an arbitrary element in Belgian French or German.

html:lang(fr-be)
html:lang(de)
:lang(fr-be) > q
:lang(de) > q

:lang(C)과 ‘|=’ 간 차이는, ‘|=’가 요소에 주어진 속성만을 대상으로 하는데 반해, :lang(C)은 UA가 문서의 시맨틱을 위한 정보를 처리대상으로 하는 데 있습니다. The difference between :lang(C) and the ‘|=’ operator is that the ‘|=’ operator only performs a comparison against a given attribute on the element, while the :lang(C) pseudo-class uses the UAs knowledge of the document's semantics to perform the comparison.

아래 HTML 예제에서, BODY만 [lang|=fr]에 매치할 것입니다. (BODY가 lang 속성을 가지고 있기 때문에) 그러나 BODY와 P는 둘 다 :lang(fr)에 매치할 것입니다. (왜냐하면 둘 다 프랑스어라서) P는 LANG 속성을 가지고 있지 않기 때문에 [lang|=fr]에 매치하지 않습니다. In this HTML example, only the BODY matches [lang|=fr] (because it has a LANG attribute) but both the BODY and the P match :lang(fr) (because both are in French). The P does not match the [lang|=fr] because it does not have a LANG attribute.

<body lang=fr>
  <p>Je suis français.</p>
</body>

6.6.4. UI 요소 상태 의사 클래스

6.6.4.1. :enabled 및 :disabled 의사 클래스

:enabled 의사 클래스는 사용 가능한 상태인 유저 인터페이스 요소를 나타냅니다. 몇가지 요소는 사용 불가능 상태에 해당합니다.

The :enabled pseudo-class represents user interface elements that are in an enabled state; such elements have a corresponding disabled state.

역으로 :disabled 의사 클래스는 사용 불가능한 상태인 유저 인터페이스 요소를 나타냅니다. 몇가지 요소는 사용 가능 상태에 해당합니다.

Conversely, the :disabled pseudo-class represents user interface elements that are in a disabled state; such elements have a corresponding enabled state.

어느게 사용 가능한 상태이며 어느게 사용 불가능한 상태인지 구성하는 건 언어에 의존합니다. 일반적으로 문서에 있어서, 대부분의 요소는 :enabled:disabled도 아닌 상태입니다.

What constitutes an enabled state, a disabled state, and a user interface element is language-dependent. In a typical document most elements will be neither :enabled nor :disabled.

노트: UI요소와 유저 인터렉션에 영향을 줄 수 있는 CSS 속성이, :enabled:disabled 매치에 영향을 주지 않습니다. 예를 들어, displayvisibility 속성은 요소의 사용 가능/사용 불가능 상태에 어떤 영향도 주지 않습니다.

Note: CSS properties that might affect a user’s ability to interact with a given user interface element do not affect whether it matches :enabled or :disabled; e.g., the display and visibility properties have no effect on the enabled/disabled state of an element.

6.6.4.2. :checked 의사 클래스

라디오 버튼과 체크박스 요소는 유저가 토글하는 요소입니다. 몇개의 메뉴 아이템은 유저가 선택할 때 "checked" 상태가 됩니다. 이러한 "checked" 상태에 있는 요소에 :checked 의사 클래스를 적용합니다. :checked 의사 클래스는 동적인 성질을 가지며, 문서의 의미적 속성의 존재에 따라 적용될 때도 있어 유저의 행동에 의해 변경되며, 모든 매체에 적용됩니다. 예를 들어 :checked 의사 클래스는 HTML4 17.2.1 섹션의 내용대로 selectedchecked 속성을 가진 요소에 먼저 적용되지만 이러한 것들은 당연히 "off"가 가능하며, 그 결과가 적용된 :checked 의사 클래스는 적용되지 않습니다.

Radio and checkbox elements can be toggled by the user. Some menu items are "checked" when the user selects them. When such elements are toggled "on" the :checked pseudo-class applies. While the :checked pseudo-class is dynamic in nature, and can altered by user action, since it can also be based on the presence of semantic attributes in the document, it applies to all media. For example, the :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked attributes as described in Section 17.2.1 of HTML4, but of course the user can toggle "off" such elements in which case the :checked pseudo-class would no longer apply.

6.6.4.3. :indeterminate 의사 클래스

노트: 유저에 의해 토글되는 라디오 버튼이나 체크박스는, 때로 체크 되어있지도 체크되어있지도 않은 불확정 상태가 됩니다. 이는 요소의 속성이나 DOM의 조작에 의해 발생합니다.

Note: Radio and checkbox elements can be toggled by the user, but are sometimes in an indeterminate state, neither checked nor unchecked. This can be due to an element attribute, or DOM manipulation.

미래의 셀렉터 스펙이 그러한 요소에 적용할 :indeterminate 의사 클래스를 도입할 가능성이 있습니다.

A future version of this specification may introduce an :indeterminate pseudo-class that applies to such elements.

6.6.5. 구조 의사 클래스

셀렉터 스펙은 문서 트리 안 정보 중 다른 심플 셀렉터나 콤비네이터로는 표현 불가능한 셀렉트를 가능하도록 구조 의사 클래스를 정의합니다.

Selectors introduces the concept of structural pseudo-classes to permit selection based on extra information that lies in the document tree but cannot be represented by other simple selectors or combinators.

단일 텍스트와 요소가 아닌 노드는, 트리 구조에서 요소의 위치를 계산할 때 계산되지 않습니다. 요소의 위치를 계산 할 때, 인덱스는 1로 시작합니다.

Standalone text and other non-element nodes are not counted when calculating the position of an element in the list of children of its parent. When calculating the position of an element in the list of children of its parent, the index numbering starts at 1.

6.6.5.1. :root 의사 클래스

:root 의사 클래스는 문서의 루트 요소를 나타냅니다. HTML 4에서는 항상 HTML 요소 입니다.

The :root pseudo-class represents an element that is the root of the document. In HTML 4, this is always the HTML element.

6.6.5.2. :nth-child() 의사 클래스

:nth-child(an+b) 의사 클래스는 문서 트리에서 어떤 요소의 자식에서 그 앞에 an+b-1개 (n은 양의 정수 혹은 0)의 형제를 가지는 상태를 나타냅니다. 의사 클래스는 요소의 자식을 a개씩 그룹으로 나누어 (마지막 그룹은 나머지를 모두 가집니다) 각각의 그룹에서 b번째 요소를 선택합니다. 예를 들어, 이 셀렉터는 table 내 행을 선택하는 일이나, 4개의 문장을 하나의 그룹으로 하여, 그룹 내 문장에 각각 다른 색을 주는 것이 가능합니다. ab의 값은 정수(양수, 음수, 0)여야 합니다. 요소의 첫번째 자식 인덱스는 1입니다.

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element. For values of a and b greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the bth element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a and b values must be integers (positive, negative, or zero). The index of the first child of an element is 1.

여기에 더해 :nth-child()는 ‘odd’ 및 ‘even’를 인수로 사용할 수 있습니다. ‘odd’는 2n+1과 동일하며, ‘even’은 2n과 동일합니다.

In addition to this, :nth-child() can take ‘odd’ and ‘even’ as arguments instead. ‘odd’ has the same signification as 2n+1, and ‘even’ has the same signification as 2n.

:nth-child() 인수는 아래 문법을 준수해야 합니다. INTEGER는 토큰 [0-9]+에 매치하며, 그 외의 토큰은 섹션 10.2 Lexical scanner에서 정의합니다.

The argument to :nth-child() must match the grammar below, where INTEGER matches the token [0-9]+ and the rest of the tokenization is given by the Lexical scanner in section 10.2:

nth
  : S* [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]? |
         ['-'|'+']? INTEGER | {O}{D}{D} | {E}{V}{E}{N} ] S*
  ;

예제:

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; }

b 값 앞에 음수기호가 있는 경우, 식 안의 "+"는 제거해야만 합니다. (b 음수 값을 표현할 "-"로 인해 결과적으로 바뀌기 때문입니다)

When the value b is preceded by a negative sign, the "+" character in the expression must be removed (it is effectively replaced by the "-" character indicating the negative value of b).

예제:

: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 */

a=0일 때, an를 포함할 필요는 없습니다. (다만, b가 이미 생략되어 있는 경우는 제외합니다) an가 인수에 포함되어있지 않고, b가 음수가 아닌 경우, b 앞에 있는 "+" 기호는 생략 가능합니다. 이 경우 문법을 :nth-child(b)같이 간단하게 작성할 수 있습니다.

When a=0, the an part need not be included (unless the b part is already omitted). When an is not included and b is non-negative, the + sign before b (when allowed) may also be omitted. In this case the syntax simplifies to :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일 때, 숫자는 선언에서 생략 가능합니다.

When a=1, or a=-1, the number may be omitted from the rule.

예제:

아래 셀렉터는 위 규칙에 따라 동일합니다. The following selectors are therefore equivalent:

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번째 요소 모두가 선택됩니다. 이 경우 a가 이미 생략되어 있는 경우는 제외하여 +b (혹은 -b)을 생략하는 게 가능합니다.

If b=0, then every ath element is picked. In such a case, the +b (or -b) part may be omitted unless the a part is already omitted.

예제:

tr:nth-child(2n+0) /* represents every even row of an HTML table */
tr:nth-child(2n) /* same */

공백 문자는 "(" 뒤, ")" 앞, anb 부분을 나누는 "+" 혹은 "-" 전후에 입력할 수 있습니다.

Whitespace is permitted after the "(", before the ")", and on either side of the "+" or "-" that separates the an and b parts when both are present.

공백 문자를 사용한 유효한 예제입니다.

: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)

만약 ab모두 0과 동일하다면, 의사 클래스는 문서 트리 내 요소를 표현하지 않습니다.

If both a and b are equal to zero, the pseudo-class represents no element in the document tree.

a 값은 음수는 가능하나, an+b가 양수 값을 가지는 경우에만 문서 트리의 요소를 나타내는 게 가능합니다.

The value a can be negative, but only the positive values of an+b, for n≥0, may represent an element in the document tree.

예제:

html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
6.6.5.3.:nth-last-child() 의사 클래스

:nth-last-child(an+b) 의사 클래스는 문서 트리 내 어떤 요소의 자식에서, 그 마지막에서 an+b-1 개(n은 양의 정수 혹은 0) 형제를 가진 상태를 나타냅니다. 인수에 대해서는 :nth-child를 참조하시길 바랍니다. :nth-child와 동일하게 ‘even’과 ‘odd’을 가질 수 있습니다.

The :nth-last-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings after it in the document tree, for any positive integer or zero value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the ‘even’ and ‘odd’ values as arguments.

예제:

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 */
6.6.5.4. :nth-of-type() 의사 클래스

:nth-of-type(an+b) 의사 클래스는 문서 트리 내 어떤 요소의 자식에서, 그 요소와 같은 요소명을 가진 요소가 그 전에 an+b-1 개(n은 양의 정수 혹은 0) 있는 상태를 나타냅니다. 인수에 대해서는 :nth-child를 참조하시길 바랍니다. :nth-child와 동일하게 ‘even’과 ‘odd’을 가질 수 있습니다.

The :nth-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the ‘even’ and ‘odd’ values.

CSS 예제:

아래 규칙으로 작성자가 이미지를 교차로 float 시킬 수 있습니다. This allows an author to alternate the position of floated images:

img:nth-of-type(2n+1) { float: right; }
img:nth-of-type(2n) { float: left; }
6.6.5.5.:nth-last-of-type() 의사 클래스

:nth-last-of-type(an+b) 의사 클래스는 문서 트리 내 어떤 요소의 자식에서 그 요소와 같은 요소명을 가진 요소가 그 후에 an+b-1개 (n은 양의 정수 혹은 0) 있는 상태를 나타냅니다. 인수에 대해서는 :nth-child를 참조하시길 바랍니다. :nth-child와 동일하게 ‘even’과 ‘odd’을 가질 수 있습니다.

The :nth-last-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same expanded element name after it in the document tree, for any zero or positive integer value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the ‘even’ and ‘odd’ values.

예제:

XHTML body 요소의 자식인 모든 h2요소 중, 첫번째와 마지막을 제외한 모든 요소를 나타내고 싶을 때 아래와 같은 셀렉터를 사용합니다. 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)

이 경우, 작성자는 :not()을 사용할 수 있지만, 길이는 크게 다르지 않습니다. 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)
6.6.5.6. :first-child 의사 클래스

:nth-child(1)과 동일합니다. :first-child 의사 클래스는 특정 요소의 첫번째 자식 요소를 나타냅니다.

Same as :nth-child(1). The :first-child pseudo-class represents an element that is the first child of some other element.

예제:

아래 셀렉터는 div 요소의 첫번째 자식인 p요소를 나타냅니다. The following selector represents a p element that is the first child of a div element:

div > p:first-child

이 셀렉터는 아래 코드에서 div 안의 p만 나타낼 수 있습니다. 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>

하지만 아래 코드에서 두번째 p요소는 나타내지 않습니다. 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>

아래 두 예제는 보통 동등합니다. The following two selectors are usually equivalent:

* > a:first-child /* a is first child of any element */
a:first-child /* Same (assuming a is not the root element) */
6.6.5.7. :last-child 의사 클래스

:nth-last-child(1)과 동일합니다. :last-child 의사 클래스는 특정 요소의 마지막 자식 요소를 나타냅니다.

Same as :nth-last-child(1). The :last-child pseudo-class represents an element that is the last child of some other element.

예제:

아래 셀렉터는 순서 있는 목록 ol 내 마지막 자식 요소인 리스트 아이템 li를 나타냅니다. The following selector represents a list item li that is the last child of an ordered list ol.

ol > li:last-child
6.6.5.8. :first-of-type 의사 클래스

:nth-of-type(1)과 동일합니다. :first-of-type 의사 클래스는 부모 요소의 자식 목록에서 해당 타입을 갖는 첫번째 형제 요소입니다.

Same as :nth-of-type(1). The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.

예제:

아래 셀렉터는 정의 목록 dl내 정의 제목 dt를 나타내며, 이 dt는 그 부모 요소의 자식 목록의 타입 중 첫번째 요소여야 합니다. The following selector represents a definition title dt inside a definition list dl, this dt being the first of its type in the list of children of its parent element.

dl dt:first-of-type

아래 예제에서 첫번째와 두번째 dt 요소는 유효하지만, 세번째 dt요소는 그렇지 않습니다. It is a valid description for the first two dt elements in the following example but not for the third one:

<dl>
 <dt>gigogne</dt>
 <dd>
  <dl>
   <dt>fusée</dt>
   <dd>multistage rocket</dd>
   <dt>table</dt>
   <dd>nest of tables</dd>
  </dl>
 </dd>
</dl>
6.6.5.9. :last-of-type 의사 클래스

:nth-last-of-type(1)과 동일합니다. :last-of-type 의사 클래스는 부모 요소의 자식 목록에서 해당 타입을 갖는 마지막 형제 요소입니다.

Same as :nth-last-of-type(1). The :last-of-type pseudo-class represents an element that is the last sibling of its type in the list of children of its parent element.

예제:

다음 셀렉터는 테이블 행 tr의 마지막 데이터 셀 td를 나타냅니다. The following selector represents the last data cell td of a table row tr.

tr > td:last-of-type
6.6.5.10. :only-child 의사 클래스

부모 요소를 가지며, 그 부모 요소에서 다른 자식 요소가 없는 요소를 나타냅니다. :first-child:last-child와 동일하며 :nth-child(1):nth-last-child(1)과도 동일하지만, 이에 비교하면 덜 특별합니다.

Represents an element that has a parent element and whose parent element has no other element children. Same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity.

6.6.5.11. :only-of-type 의사

부모 요소를 가지며, 그 부모 요소에서 같은 요소명을 가진 다른 자식 요소가 없는 요소를 나타냅니다. :first-of-type:last-of-type과 동일하며 :nth-of-type(1):nth-last-of-type(1)과도 동일하지만, 이에 비교하면 덜 특별합니다.

Represents an element that has a parent element and whose parent element has no other element children with the same expanded element name. Same as :first-of-type:last-of-type or :nth-of-type(1):nth-last-of-type(1), but with a lower specificity.

6.6.5.12. :empty 의사 클래스

:empty 의사 클래스는 자식을 가지지 않은 요소를 나타냅니다. 문서 트리 관점에서 생각하면, 요소 노드와 콘텐츠 노드 (DOM [DOM-LEVEL-3-CORE] 텍스트 노트, CDATA 노드, 엔티티 참조 같은)가 0이 아닌 길이의 정보를 가진 경우, 이는 요소가 비어있는 지 확인하는데 영향을 주는 것으로써 처리해야만 합니다. 주석, 처리 명령, 그 외 노드는 요소가 공백인지 확인하는데 영향을 주지 않습니다.

The :empty pseudo-class represents an element that has no children at all. In terms of the document tree, only element nodes and content nodes (such as DOM [DOM-LEVEL-3-CORE] text nodes, CDATA nodes, and entity references) whose data has a non-zero length must be considered as affecting emptiness; comments, processing instructions, and other nodes must not affect whether an element is considered empty or not.

예제:

아래 코드에서 p:empty는 유효합니다. p:empty is a valid representation of the following fragment:

<p></p>

아래 코드에서 foo:empry는 유효하지 않습니다. 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>

6.6.6. 공백

이 섹션은 의도적으로 비어있습니다. (이 섹션에는 원래 :contains() 의사 클래스가 정의되어 있었습니다)

This section intentionally left blank. (This section previously defined a :contains() pseudo-class.)

6.6.7. 부정 의사 클래스

부정 의사 클래스, :not(X)은 함수 표기식이며, (부정 의사 클래스 본인을 제외한) 심플 셀렉터를 인수로 가집니다. 부정 의사 클래스는 인수 내 요소에서 표현하지 않는 요소를 나타냅니다.

The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself) as an argument. It represents an element that is not represented by its argument.

부정 의사 클래스는 포함할 수 없습니다. :not(:not(...))은 유효하지 않습니다. 또 의사 요소는 심플 셀렉터가 아니기 때문에, :not()에 넣을 수 있는 유효한 인수가 아닙니다.

Negations may not be nested; :not(:not(...)) is invalid. Note also that since pseudo-elements are not simple selectors, they are not a valid argument to :not().

예제:

아래 셀렉터는 HTML 문서 내 button 중, 사용 불가능하지 않은(즉 사용 가능한) 것 모두에 매치합니다. The following selector matches all button elements in an HTML document that are not disabled.

button:not([DISABLED])

아래 셀렉터는 FOO 요소를 제외한 모든 요소를 나타냅니다. The following selector represents all but FOO elements.

*:not(FOO)

아래 셀렉터는, 링크가 아닌 모든 HTML 요소를 나타냅니다. The following group of selectors represents all HTML elements except links.

html|*:not(:link):not(:visited)

기본 네임스페이스 선언은, 부정 의사 클래스의 인수에 영향을 주지 않습니다. 그러나, 인수가 전역 셀렉터 혹은 타입 셀렉터인 경우를 제외합니다.

Default namespace declarations do not affect the argument of the negation pseudo-class unless the argument is a universal selector or a type selector.

예제:

기본 네임스페이스가 "http://example.com"이라고 했을 때, 아래 셀렉터는 그 네임스페이스에 속하지 않은 모든 요소를 나타냅니다. Assuming that the default namespace is bound to "http://example.com/", the following selector represents all elements that are not in that namespace:

*|*:not(*)

아래 셀렉터는 네임스페이스를 묻지 않고, 호버 상태가 아닌 요소 모두에 매치합니다. 이는 기본 네임스페이스에 속하며, 호버 상태가 아닌 요소에 한정하지 않습니다. 여기에 더해, 기본 네임스페이스에 속하지 않는 요소가 호버 상태인 경우, 그 요소는 매치하지 않습니다. The following selector matches any element that is not being hovered, regardless of its namespace. In particular, it is not limited to only matching elements in the default namespace that are not being hovered, and elements not in the default namespace don't match the rule when they are being hovered.

*|*:not(:hover)

노트: not() 의사 클래스를 사용해서 의미 없는 셀렉터를 작성할 수 있습니다. 예를 들어, :not(*|*) 등의 요소도 나타내지 않습니다. 그 외에도, foo:not(bar)같은 셀렉터도 작성할 수 있습니다. 이는 foo와 동일하지만, foo보다 더 높은 상세도를 가집니다.

Note: the :not() pseudo allows useless selectors to be written. For instance :not(*|*), which represents no element at all, or foo:not(bar), which is equivalent to foo but with a higher specificity.

7. 의사 요소

의사 요소는 문서 언어에 의해 정의된 문서 트리에 추상적인 요소를 생성합니다. 예를 들어, 문서 언어는 요소 내용의 첫번째 문자나 첫번째 행에 접근하는 수단을 제공하지 않습니다. 의사 요소에 의해 본래 접근 불가능한 정보를 다루는 게 가능합니다. 의사 요소는 원래 문서에 존재하지 않는 내용을 참조하는 방법도 제공합니다. (예: ::before, ::after 의사 요소는 생성된 콘텐츠에 접근할 수 있게 합니다)

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. Pseudo-elements allow authors to refer to this otherwise inaccessible information. Pseudo-elements may also provide authors a way to refer to content that does not exist in the source document (e.g., the ::before and ::after pseudo-elements give access to generated content).

의사 요소는 의사 요소명 앞에 두개의 콜론 (::)을 작성해 생성합니다.

A pseudo-element is made of two colons (::) followed by the name of the pseudo-element.

:: 표기법은 의사 클래스와 의사 요소를 구별하기 위해, 셀렉터 레벨 3에서 도입했습니다. 현재 스타일시트와 호환하기 위해, UA는 CSS1, CSS2에서 도입된 콜론 1개 표기법으로 표현하는 의사 요소(:first-line, :first-letter, :before, :after)도 지원해야만 합니다. 이 호환방안은 레벨 3에서 도입된 새로운 클래스에는 적용되지 않습니다.

This :: notation is introduced by the current document in order to establish a discrimination between pseudo-classes and pseudo-elements. For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in this specification.

의사 요소는 셀렉터당 1개만 사용 가능합니다. 셀렉터에 의사 요소가 있는 경우, 셀렉터의 대상을 나타내는 심플 셀렉터 시퀀스 뒤에 나타나야만 합니다. 노트: 미래 버전의 셀렉터 스펙에서 셀렉터당 의사 요소를 여러개 허용할 가능성이 있습니다

Only one pseudo-element may appear per selector, and if present it must appear after the sequence of simple selectors that represents the subjects of the selector. Note: A future version of this specification may allow multiple pseudo-elements per selector.

7.1. ::first-line 의사 요소

::first-list 의사 요소는 요소의 첫번째 줄 콘텐츠를 나타냅니다.

The ::first-line pseudo-element describes the contents of the first formatted line of an element.

CSS 예제:

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

위 규칙은 "모든 p 요소에서, 첫번째 줄을 대문자로 표기하라"는 의미를 가집니다.

The above rule means "change the letters of the first line of every p element to uppercase".

p::first-line 셀렉터는 실존하는 문서 요소에 매치하지 않습니다. 이 셀렉터는, 적합 UA가 모든 p 요소의 시작 부분에 넣는 의사 요소에 매치합니다.

The selector p::first-line does not match any real document element. It does match a pseudo-element that conforming user agents will insert at the beginning of every p element.

첫번째 줄의 길이는, 페이지 폭, 폰트 사이즈 등 여러 조건에 의존합니다. 아래와 같은 HTML 문장을 생각해봅시다:

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.

이 문장은 UA에 의해, ::first-line가상 태그 시퀀스를 포함하도록 "재작성" 될 수 있습니다. 이 가상 태그 시퀀스는 어떻게 속성이 상속되어야 하는지 알기 쉽게 합니다.

This 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 </P::first-line> 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>

가상 요소가 실제로 존재하는 요소에 의해 분해되는 경우 상정 가능한 결과는, 가상 태그 시퀀스로 인해 그 요소가 다히며, 직후에 다시 여는 형태를 생각할 수 있습니다. 첫번째 문장이 span 요소로 마크업 된 상황을 생각해봅시다:

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>

유저 에이전트는 ::first-line으로 인한 가상 태그 시퀀스를 넣을 때, span의 시작 태그와 종료 태그를 아래와 같이 넣을 거라 생각할 수 있습니다.

the user agent could simulate 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>

7.1.1. CSS에서 정의된 첫번째 형태를 가진 행

CSS에서, ::first-line 의사 요소는 block box, inline-block, table-caption, table-cell 같은 블럭류 컨테이너에서만 기능합니다.

In CSS, the ::first-line pseudo-element can only have an effect when attached to a block-like container such as a block box, inline-block, table-caption, or table-cell.

요소의 첫번째 형태를 가진 행은, 같은 플로우 안의 자손 블 (position이나 float에 의해 통상 flow에서 벗어난 블럭이 아닌 것)에 의존할 수도 있습니다. 예를 들어, <DIV><P>This line...</P></DIV>라는 마크업에서 DIV의 첫번째 행은, p의 첫번째 행이 됩니다. (PDIV 양쪽 다 블럭이라고 했을 때)

The first formatted line of an element may occur inside a block-level descendant in the same flow (i.e., a block-level descendant that is not out-of-flow due to floating or positioning). For example, the first line of the DIV in <DIV><P>This line...</P></DIV> is the first line of the P (assuming that both P and DIV are block-level).

table-cell이나 inline-block의 첫번째 행은, 선조 요소의 첫번째 형태를 가진 행이 되지 않습니다. 즉, <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> 마크업의 DIV의 형태를 가진 행은 "Hello"가 아닙니다.

The first line of a table-cell or inline-block cannot be the first formatted line of an ancestor element. Thus, in <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> the first formatted line of the DIV is not the line "Hello".

노트: <p><br>First... 마크업에서 p의 첫번째 행에는 문자를 포함하지 않습니다(br은 HTML4 기본 스타일이 적용되어있는 것으로 간주어집니다). 따라서, "First"라는 단어는 첫번째 형태를 가진 행에 포함하지 않습니다.

Note: Note that the first line of the p in this fragment: <p><br>First... doesn't contain any letters (assuming the default style for br in HTML 4). The word "First" is not on the first formatted line.

UA는 ::first-line 의사 요소에 대해, 가상의 여는 태그가 그걸 둘러싼 요소 중 가장 안쪽에 있는 블럭 요소 중 중첩되는 것으로 행동해야 합니다. (단 CSS1과 CSS2는 이 상태에 대해 어떤 설명도 하지 않기 때문에, 제작자는 이 행동에 의존하지 않아도 됩니다) 예를 들어, 아래와 같은 가상 태그 시퀀스가 있습니다.

A UA should act as if the fictional start tags of the ::first-line pseudo-elements were nested just inside the innermost enclosing block-level element. (Since CSS1 and CSS2 were silent on this case, authors should not rely on this behavior.) For example, the fictional tag sequence for

<DIV>
  <P>First paragraph</P>
  <P>Second paragraph</P>
</DIV>

<DIV>
  <P><DIV::first-line><P::first-line>First paragraph</P::first-line></DIV::first-line></P>
  <P><P::first-line>Second paragraph</P::first-line></P>
</DIV>

::first-line 의사 요소는 인라인 요소와 비슷하지만, 몇가지 제약이 있습니다. ::first-line 가상 요소에는 아래 CSS 속성만 허용합니다: font 속성, color 속성, background 속성, ‘word-spacing’, ‘letter-spacing’, ‘text-decoration’, ‘vertical-align’, ‘text-transform’, ‘line-height’. UA에서 다른 속성을 허용할 수도 있습니다.

The ::first-line pseudo-element is similar to an inline-level element, but with certain restrictions. The following CSS properties apply to a ::first-line pseudo-element: font properties, color property, background properties, ‘word-spacing’, ‘letter-spacing’, ‘text-decoration’, ‘vertical-align’, ‘text-transform’, ‘line-height’. UAs may apply other properties as well.

CSS 상속에 있어, 자식 요소의 일부가 첫번째 행인 경우 ::first-line 의사 요소에 적용 가능한 속성만을 ::first-line 의사 요소에서 상속받습니다. 그 외의 속성에 대해서는, ::first-line의 부모 중 의사 요소가 아닌 것에서 상속합니다. 첫번째 행이 아닌 자식 요소의 일부는 그 부모에서 상속합니다.

During CSS inheritance, the portion of a child element that occurs on the first line only inherits properties applicable to the ::first-line pseudo-element from the ::first-line pseudo-element. For all other properties inheritence is from the non-pseudo-element parent of the first line pseudo element. (The portion of a child element that does not occur on the first line always inherits from the parent of that child.)

7.2. ::first-letter 의사 요소

::first-letter 의사 요소는 요소의 첫번째 문자를 나타냅니다. 해당 줄에서 요소의 앞에 이미지나 인라인 테이블 등 다른 내용이 있는 경우 매치하지 않습니다. ::first-letter 의사 요소는 "initial caps"와 "drop caps" 같이 ㅌ자주 사용하는 타이포 그래피 효과를 얻기 위해 사용합니다.

The ::first-letter pseudo-element represents the first letter of an element, if it is not preceded by any other content (such as images or inline tables) on its line. The ::first-letter pseudo-element may be used for "initial caps" and "drop caps", which are common typographical effects.

Unicode에서 "open" (Ps), "close" (Pe), "initial" (Pi), "final" (Pf) and "other" (Po) 클래스에 분류되는 기호가 행의 첫번째 문자거나 행의 첫번째 문자 직후에 나오는 경우, 그 또한 ::first-letter에 포함하여야 합니다. [UNICODE]

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

Quotes that precede the first letter should be included.

::first-letter는 첫번째 글자가 숫자인 경우, 예를 들어 "67 million dollares is a lot of money"라는 문장에서 "6"에도 적용됩니다.

The ::first-letter also applies if the first letter is in fact a digit, e.g., the "6" in "67 million dollars is a lot of money."

노트: 몇몇 케이스에서, ::first-letter 의사 클래스는 행 안에 약물(기호, 구두점, 괄호)이 아닌 문자를 포함해야 합니다. 예를 들어, 결합 문자는 그 기본 문자와 함께 보유되야 합니다. 또, 몇몇 언어에서는 문자 연결 처리에 특정 룰을 줄 수도 있습니다. UA에 따른 ::first-letter 정의는, 적어도 UAX29에서 정의된 규칙의 자소 클러스터를 포함해야하며, 가능하다면 그 이상이어도 좋습니다. 예를 들어 네덜란드어에서 "ij"라는 결합문자가 있을 때, 두 문자 모두 ::first-letter 의사 요소로 고려되야 합니다. [UAX29]

Note: In some cases the ::first-letter pseudo-element should include more than just the first non-punctuation character on a line. For example, combining characters must be kept with their base character. Additionally, some languages may have specific rules about how to treat certain letter combinations. The UA definition of ::first-letter should include at least the default grapheme cluster as defined by UAX29 and may include more than that as appropriate. In Dutch, for example, if the letter combination "ij" appears at the beginning of an element, both letters should be considered within the ::first-letter pseudo-element. [UAX29]

::first-letter 의사 요소를 구성하는 문자가 같은 요소에 존재하지 않는 경우, 예를 들어, <p>'<em>T... 마크업에서 첫 문자가 "T가 되는 경우 UA는 ::first-letter 의사 요소를 한쪽 요소에 생성하거나, 양쪽 요소에 생성하거나, 간단히 생성하지 않는 방법을 취할 수 있습니다.

If the letters that would form the ::first-letter are not in the same element, such as "‘T’" in <p>'<em>T..., the UA may create a ::first-letter pseudo-element from one of the elements, both elements, or simply not create a pseudo-element.

마찬가지로, 블럭 안 첫번째 문자가 첫번째 행이 아닌 경우 (예를 들어 쌍방향 텍스트의 재구성 등에 의해) UA는 의사 요소를 생성할 필요가 없습니다.

Similarly, if the first letter(s) of the block are not at the start of the line (for example due to bidirectional reordering), then the UA need not create the pseudo-element(s).

예제:

다음 CSS와 HTML예는 어떻게 서로 다른 의사 요소가 관계를 이루는 지 설명합니다. 각 P 요소의 첫번째 문자는 ’24pt‘ 폰트 사이즈에 green 색상일 것이며. 첫번째 줄의 나머지 문자는 ‘blue’가 될 것이며, 그 외의 모든 문자는 ‘red’로 표기될 것입니다. The following CSS and HTML 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>

"ends" 앞에 line break가 있다고 판정하면, 이 마크업에 있어 가상 태그 시퀀스는 아래와 같이 나타납니다. 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>

::first-line 요소 안에 ::first-letter 요소가 존재합니다. ::first-line 요소에 설정된 속성은 ::first-letter 요소에 상속되지만, 같은 속성이 ::first-letter 요소에 설정된 경우, 그 속성은 덮어씌워집니다. 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.

첫번째 문자는 반드시 첫번쨰 줄에 있어야 합니다. 예를 들어, HTML 마크업 <p><br>First...에서, 첫번째 문자에 어떤 문자도 포함하지 않습니다. 따라서 ::first-letter는 아무것도 포함하지 않습니다. (HTML4에서 br의 기본 스타일이 적용되어 있다고 취급합니다.) 따라서, 단어 "First"의 "F"에 매치하지 않습니다.

The first letter must occur on the first formatted line. For example, in this HTML fragment: <p><br>First... the first line doesn't contain any letters and ::first-letter doesn't match anything (assuming the default style for br in HTML 4). In particular, it does not match the "F" of "First."

7.2.1. CSS에서 적용

CSS에서, ::first-letter 의사 요소는 block, list-item, table-cell, table-caption, inline-block 요소 같은 블럭처럼 동작하는 콘테이너에 사용할 수 있습니다. 노트: 차기 셀렉터 스펙에서, 다른 디스플레이 타입에도 ::first-letter 의사 요소를 지정 가능하게 될 수 있습니다.

In CSS, the ::first-letter pseudo-element applies to block-like containers such as block, list-item, table-cell, table-caption, and inline-block elements. Note: A future version of this specification may allow this pseudo-element to apply to more display types.

::first-letter 의사 클래스는 텍스트를 포함한 요소, 혹은 같은 flow에 속하는 자식이 텍스트를 가진 경우에 사용할 수 있습니다. UA는 가상의 ::first-letter 시작 태그가 첫번째 문자 직후에 있는 듯이 행동해야 합니다. 이는 텍스트가 자식에 속하는 경우에도 사용 가능합니다.

The ::first-letter pseudo-element can be used with all such elements that contain text, or that have a descendant in the same flow that contains text. A UA should act as if the fictional start tag of the ::first-letter pseudo-element is just before the first text of the element, even if that first text is in a descendant.

예제:

HTML코드를 위한 가상 태그 시퀀스 The fictional tag sequence for this HTML fragment:

<div>
<p>The first text.

는: is:

<div>
<p><div::first-letter><p::first-letter>T</...></...>he first text.

CSS에서 table-cell이나 inline-block의 첫번째 문자는, 조상의 첫번째 문자가 되지 않습니다. 즉 <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> 마크업에서 DIV의 첫번째 문자는 "H"가 아닙니다. 이 경우 DIV는 첫번째 문자를 가지지 않습니다.

In CSS the first letter of a table-cell or inline-block cannot be the first letter of an ancestor element. Thus, in <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> the first letter of the DIV is not the letter "H". In fact, the DIV doesn't have a first letter.

요소가 리스트 아이템 (‘display: list-item’)인 경우 ::first-letter는 부모 박스의 마커 다음에 오는 첫번째 문자에 적용됩니다. UA는 ‘list-style-position: inside’인 리스트 아이템에 지정된 ::first-letter를 무시해도 괜찮습니다. 요소에 ::before 혹은 ::after로 내용이 주어진 경우, ::first-letter는 그 내용을 포함한 콘텐츠에서 결정합니다.

If an element is a list item (‘display: list-item’), the ::first-letter applies to the first letter in the principal box after the marker. UAs may ignore ::first-letter on list items with ‘list-style-position: inside’. If an element has ::before or ::after content, the ::first-letter applies to the first letter of the element including that content.

예제:

p::before {content: "Note: "} 규칙이 주어진 경우, 셀렉터 p::first-letter는 'Note"의 "N"에 매치합니다. After the rule p::before {content: "Note: "}, the selector p::first-letter matches the "N" of "Note".

CSS에서 ::first-letter 의사 요소는 ‘float’가 ‘none’인 경우, 인라인 레벨 요소와 비슷하게 동작합니다. ::first-letter 의사 요소에 적용 가능한 속성은 font 관련 속성, ‘text-decoration’, ‘text-transform’, ‘letter-spacing’, ‘word-spacing’ (when appropriate), ‘line-height’, ‘float’, ‘vertical-align’ (‘float’가 ‘none’인 경우에만), margin 속성, padding 속성, border 속성, color 속성, background 속성입니다. UA는 line-height, width 및 height를 문자의 형태에 기초로 둘 수 있으며, 이는 보통 요소와는 다릅니다.

In CSS a ::first-line pseudo-element is similar to an inline-level element if its ‘float’ property is ‘none’ otherwise, it is similar to a floated element. The following properties that apply to ::first-letter pseudo-elements: font properties, ‘text-decoration’, ‘text-transform’, ‘letter-spacing’, ‘word-spacing’ (when appropriate), ‘line-height’, ‘float’, ‘vertical-align’ (only if ‘float’ is ‘none’), margin properties, padding properties, border properties, color property, background properties. UAs may apply other properties as well. To allow UAs to render a typographically correct drop cap or initial cap, the UA may choose a line-height, width and height based on the shape of the letter, unlike for normal elements.

예제:

다음 CSS와 HTML은, initial cap 표시 예입니다. ::first-letter 의사 요소에서 상속된 ‘line-height’의 값은 1.1이지만, 이 예에서는 UA가 첫번째 문자의 높이를 다르게 설계하여, 1번째 줄과 2번째 줄 사이에 불필요한 공백이 생기지 않도록 조정하고 있는 점에 주의하시길 바랍니다. 또한 첫번째 문자에 있어 가상의 여는 태그가 span 안에 있기 때문에, span에 지정된 font-weight가 bold가 아닌 normal인 점에 주의하시길 바랍니다.

This CSS and HTML example shows a possible rendering of an initial cap. Note that the ‘line-height’ that is inherited by the ::first-letter pseudo-element is 1.1, but the UA in this example has computed the height of the first letter differently, so that it doesn't cause any unnecessary space between the first two lines. Also note that the fictional start tag of the first letter is inside the span, and thus the font weight of the first letter is normal, not bold as the span:

p { line-height: 1.1 }
p::first-letter { font-size: 3em; font-weight: normal }
span { font-weight: bold }
...
<p><span>Het hemelsche</span> gerecht heeft zich ten lange lesten<br>
Erbarremt over my en mijn benaeuwde vesten<br>
En arme burgery, en op mijn volcx gebed<br>
En dagelix geschrey de bange stad ontzet.

Image illustrating the ::first-letter pseudo-element

아래 CSS는 두 줄에 걸쳐 표현하는 drop cap을 의미합니다. The following CSS will make a drop cap initial letter span about two lines:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
 <HEAD>
  <TITLE>Drop cap initial letter</TITLE>
  <STYLE type="text/css">
   P               { font-size: 12pt; line-height: 1.2 }
   P::first-letter { font-size: 200%; 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

가상 태그 시퀀스는: 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>

::first-line 의사 요소는 여는 태그가 블럭 요소의 여는 태그 직후에 들어가고, ::first-letter 의사 요소 태그는 내용 (첫번째 문자)에 인접하는 점에 주의하시길 바랍니다.

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 block element.

전통적인 drop cap 효과를 구현하기 위해, UA는 폰트 사이즈의 개산을 행해 베이스라인을 정리하는 게 가능합니다. 또, 정형화할 때 그리프의 아웃라인을 가미할 수 있습니다.

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.

7.3. 공백

이 섹션은 의도적으로 비어있습니다. (이 섹션에는 원래 :selection 의사 요소가 정의되어 있었습니다)

This section intentionally left blank. (This section previously defined a ::selection pseudo-element.)

7.4. ::before 및 ::after 의사 요소

::before::after 의사 요소는 요소의 내용 앞이나 뒤에 있는 생성 콘텐츠(generated content)를 나타내기 위해 사용합니다. 이러한 의사 요소는 CSS 2.1에서 정의하고 있습니다[CSS21].

The ::before and ::after pseudo-elements can be used to describe generated content before or after an element's content. They are explained in CSS 2.1 [CSS21].

::before 혹은 ::after에 의해 생성된 내용을 가지는 요소에 ::first-letter의사 요소와 ::first-line 의사 요소가 적용 되는 경우, ::first-letter::first-line은 각각 생성된 내부를 포함한 문자 혹은 행에 적용됩니다.

When the ::first-letter and ::first-line pseudo-elements are applied to an element having content generated using ::before or ::after, they apply to the first letter or line of the element including the generated content.

8. 콤비네이터

8.1. 자손 콤비네이터

문서 트리 안에서 어떤 요소의 자손 요소를 설명하는 셀렉터가 필요할 것입니다. (예를 들어 H1 요소 안에 있는 EM 요소) 자손 콤비네이터는 이런 관계를 나타낼 때 사용합니다. 자손 콤비네이터는 공백문자로 2개의 심플 셀렉터 시퀀스를 구분하여 표현합니다. "A B" 형태의 셀렉터는 A요소의 자손 요소인 B요소를 나타냅니다.

At times, authors may want selectors to describe an element that is the descendant of another element in the document tree (e.g., "an EM element that is contained within an H1 element"). Descendant combinators express such a relationship. A descendant combinator is whitespace that separates two sequences of simple selectors. A selector of the form "A B" represents an element B that is an arbitrary descendant of some ancestor element A.

예제:

예를 들어, 아래와 같은 형테의 셀렉터를 생각할 수 있습니다. For example, consider the following selector:

h1 em

이는 h1 요소의 자손인 em 요소를 나타냅니다. 이는 유효하고 타당한 셀렉터이며, 다음 마크업 중 일부를 나타냅니다. It represents an em element being the descendant of an h1 element. It is a correct and valid, but partial, description of the following fragment:

<h1>This <span class="myclass">headline
is <em>very</em> important</span></h1>

아래와 같은 셀렉터가 있습니다: The following selector:

div * p

이는 div 요소의 손이나 증손 요소인 p 요소를 나타냅니다. "*" 앞에 있는 공백 문자가 전역 셀렉터의 일부가 아님에 주의하시길 바랍니다. 이 공백문자는 콤비네이터이며, div가 어떤 요소의 조상이며, 어떤 요소도 또한 p요소의 부모임을 나타냅니다. represents a p element that is a grandchild or later descendant of a div element. Note the whitespace on either side of the "*" is not part of the universal selector; the whitespace is a combinator indicating that the div must be the ancestor of some element, and that that element must be an ancestor of the p.

아래 셀렉터는 자손 콤비네이터와 속성 셀렉터를 조합하여, div 요소 안에 있는 p 요소의 자손 중, href 속성이 정의된 요소를 나타냅니다. The following selector, which combines descendant combinators and attribute selectors, represents an element that (1) has the href attribute set and (2) is inside a p that is itself inside a div:

div p *[href]

8.2. 자식 콤비네이터

자식 콤비네이터는 두 요소의 부모자식 관계를 표현합니다. 자식 콤비네이터는 두 심플 셀렉터 시퀀스를 "~보다 큰" (U+003E, >) 기호로 구분하여 표현합니다.

A child combinator describes a childhood relationship between two elements. A child combinator is made of the "greater-than sign" (U+003E, >) character and separates two sequences of simple selectors.

예제:

아래 셀렉터는 body의 자식 요소인 p 요소를 나타냅니다. The following selector represents a p element that is child of body:

body > p

아래는 자손 콤비네이터와 자식 콤비네이터를 결합한 예제입니다. The following example combines descendant combinators and child combinators.

div ol>li p

이 셀렉터는 div 요소의 자손인 ol 요소의 자식 요소 li의 자손 요소인 p요소를 나타냅니다. ">" 콤비네이터 직후에 임의로 넣을 수 있는 공백문자가 생략되어 있는 점에 주의하시길 바랍니다.

It represents a p element that is a descendant of an li element; 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 white space around the ">" combinator has been left out.

어떤 요소의 자식 중 1번째 자식만 선택하고 싶은 경우, :first-child 의사 클래스 섹션을 참조하시길 바랍니다.

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

8.3. 형제 콤비네이터

형제 콤비네이터에는 인접 형제 콤비네이터와 일반 형제 콤비네이터 두종류가 있습니다. 양쪽 케이스 모두 요소간 인접관계를 표현할 때 요소가 아닌 노드 (요소 사이 텍스트 등)은 무시합니다.

There are two different sibling combinators: the adjacent sibling combinator and the general sibling combinator. In both cases, non-element nodes (e.g. text between elements) are ignored when considering adjacency of elements.

8.3.1. 인접 형제 콤비네이터

인접 형제 콤비네이터는 두개의 심플 셀렉터 시퀀스 사이에 "덧셈 기호"(U+002B, +)를 넣어 작성합니다. 두 시퀀스에 의해 표현된 요소는 트리 위에서 같은 부모를 가져야 하며, 첫번째로 나타나는 요소가 두번째로 나타나는 요소의 바로 앞에 있어야 합니다.

The adjacent sibling combinator is made of the "plus sign" (U+002B, +) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence immediately precedes the element represented by the second one.

예제:

아래 셀렉터는 math 요소 바로 뒤에 나타나는 p 요소를 나타냅니다. The following selector represents a p element immediately following a math element:

math + p

아래 에제는 이전 예제와 비슷해 보이지만, 속성 셀렉터가 추가되어있습니다. h2 요소 직전에 나타나는 h1요소에는 class="opener"가 주어져 있어야 하는 제약이 있습니다.

The following selector is conceptually similar to the one in the previous example, except that it adds an attribute selector — it adds a constraint to the h1 element, that it must have class="opener":

h1.opener + h2

8.3.2. 일반 형제 콤비네이터

일반 형제 콤비네이터는 두개의 심플 셀렉터 시퀀스 사이에 "물결 기호"(U+002B, ~)를 넣어 작성합니다. 두 시퀀스는 문서 트리에서 같은 요소를 가져야 하며, 1번째로 나타나는 요소가 2번째로 나타나는 요소의 앞(바로 앞이 아니어도 좋습니다)에 있어야 합니다.

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

예제:

h1 ~ pre

이 셀렉터는 h1에 이어지는 pre 요소를 나타냅니다. 이는 유효하고 타당한 셀렉터이며, 아래와 같은 마크업의 일부를 나타냅니다.

represents a pre element following an h1. It is a correct and valid, but partial, description of:

<h1>Definition of the function a</h1>
<p>Function a(x) has to be applied to all figures in the table.</p>
<pre>function a(x) = 12x/13.5</pre>

9. 셀렉터의 상세도 계산

셀렉터의 상세도는 다음 순서로 계산합니다.

A selector's specificity is calculated as follows:

부정 의사 클래스 안의 셀렉터도 다른 셀렉터와 동일하게 셉니다. 그러나, 부정 의사 클래스 자신은 의사 클래스로 세지 않습니다.

Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.

3개의 숫자를 결합한 게 셀렉터의 상세도입니다. (large base의 숫자 시스템을 기반으로 합니다)

Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.

예제:

*               /* a=0 b=0 c=0 -> specificity =   0 */
LI              /* a=0 b=0 c=1 -> specificity =   1 */
UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */

노트:같은 심플 셀렉터의 반복도 허용하며, 반복함에 따라 상세도도 상승합니다.

Note: Repeated occurrances of the same simple selector are allowed and do increase specificity.

노트: HTML의 style 속성에 따른 상세도는 CSS 2.1에서 설명합니다[CSS21].

Note: the specificity of the styles specified in an HTML style attribute is described in CSS 2.1. [CSS21].

10. 셀렉터 문법

10.1. 문법

문법은 셀렉터의 구문 정의 하에 있습니다. 이는 전역 LL(1)과 지역 LL(2)가 있습니다. (하지만 구문 파싱 컨벤션을 표현하지 않기 때문에, 대부분의 UA는 직접 사용하지 않도록 주의를 요합니다) 생성 형식은 인간의 소비와 일부 Yacc([YACC] 참조)를 넘은 약칭 표기법을 사용합니다.

The grammar below defines the syntax of Selectors. It is globally LL(1) and can be locally LL(2) (but note that most UAs should not use it directly, since it doesn't express the parsing conventions). The format of the productions is optimized for human consumption and some shorthand notations beyond Yacc (see [YACC]) are used:

The productions are:

selectors_group
  : selector [ COMMA S* selector ]*
  ;

selector
  : simple_selector_sequence [ combinator simple_selector_sequence ]*
  ;

combinator
  /* combinators can be surrounded by whitespace */
  : PLUS S* | GREATER S* | TILDE S* | S+
  ;

simple_selector_sequence
  : [ type_selector | universal ]
    [ HASH | class | attrib | pseudo | negation ]*
  | [ HASH | class | attrib | pseudo | negation ]+
  ;

type_selector
  : [ namespace_prefix ]? element_name
  ;

namespace_prefix
  : [ IDENT | '*' ]? '|'
  ;

element_name
  : IDENT
  ;

universal
  : [ namespace_prefix ]? '*'
  ;

class
  : '.' IDENT
  ;

attrib
  : '[' S* [ namespace_prefix ]? IDENT S*
        [ [ PREFIXMATCH |
            SUFFIXMATCH |
            SUBSTRINGMATCH |
            '=' |
            INCLUDES |
            DASHMATCH ] S* [ IDENT | STRING ] S*
        ]? ']'
  ;

pseudo
  /* '::' starts a pseudo-element, ':' a pseudo-class */
  /* Exceptions: :first-line, :first-letter, :before and :after. */
  /* Note that pseudo-elements are restricted to one per selector and */
  /* occur only in the last simple_selector_sequence. */
  : ':' ':'? [ IDENT | functional_pseudo ]
  ;

functional_pseudo
  : FUNCTION S* expression ')'
  ;

expression
  /* In CSS3, the expressions are identifiers, strings, */
  /* or of the form "an+b" */
  : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
  ;

negation
  : NOT S* negation_arg S* ')'
  ;

negation_arg
  : type_selector | universal | HASH | class | attrib | pseudo
  ;

10.2. Lexical scanner

The following is the tokenizer, written in Flex (see [FLEX]) notation. The tokenizer is case-insensitive.

The two occurrences of "\377" represent the highest character number that current versions of Flex can deal with (decimal 255). They should be read as "\4177777" (decimal 1114111), which is the highest possible code point in Unicode/ISO-10646. [UNICODE]

%option case-insensitive

ident     [-]?{nmstart}{nmchar}*
name      {nmchar}+
nmstart   [_a-z]|{nonascii}|{escape}
nonascii  [^\0-\177]
unicode   \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
escape    {unicode}|\\[^\n\r\f0-9a-f]
nmchar    [_a-z0-9-]|{nonascii}|{escape}
num       [0-9]+|[0-9]*\.[0-9]+
string    {string1}|{string2}
string1   \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*\"
string2   \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*\'
invalid   {invalid1}|{invalid2}
invalid1  \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*
invalid2  \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*
nl        \n|\r\n|\r|\f
w         [ \t\r\n\f]*

D         d|\\0{0,4}(44|64)(\r\n|[ \t\r\n\f])?
E         e|\\0{0,4}(45|65)(\r\n|[ \t\r\n\f])?
N         n|\\0{0,4}(4e|6e)(\r\n|[ \t\r\n\f])?|\\n
O         o|\\0{0,4}(4f|6f)(\r\n|[ \t\r\n\f])?|\\o
T         t|\\0{0,4}(54|74)(\r\n|[ \t\r\n\f])?|\\t
V         v|\\0{0,4}(58|78)(\r\n|[ \t\r\n\f])?|\\v

%%

[ \t\r\n\f]+     return S;

"~="             return INCLUDES;
"|="             return DASHMATCH;
"^="             return PREFIXMATCH;
"$="             return SUFFIXMATCH;
"*="             return SUBSTRINGMATCH;
{ident}          return IDENT;
{string}         return STRING;
{ident}"("       return FUNCTION;
{num}            return NUMBER;
"#"{name}        return HASH;
{w}"+"           return PLUS;
{w}">"           return GREATER;
{w}","           return COMMA;
{w}"~"           return TILDE;
":"{N}{O}{T}"("  return NOT;
@{ident}         return ATKEYWORD;
{invalid}        return INVALID;
{num}%           return PERCENTAGE;
{num}{ident}     return DIMENSION;
"<!--"           return CDO;
"-->"            return CDC;

\/\*[^*]*\*+([^/*][^*]*\*+)*\/                    /* ignore comments */

.                return *yytext;

11. 프로필

셀렉터를 이용하는 스펙은 어떤 셀렉터를 허용하며 어떤 셀렉터를 허용하지 않는지 나타내는 서브셋 정의 및 스펙에서 셀렉터의 의미를 설명해야합니다.

Each specification using Selectors must define the subset of Selectors it allows and excludes, and describe the local meaning of all the components of that subset.

표준에 준하지 않는 예제입니다:

Non normative examples:

Selectors profile
Specification CSS level 1
Accepts type selectors
class selectors
ID selectors
:link, :visited and :active pseudo-classes
descendant combinator
::first-line and ::first-letter pseudo-elements
Excludes

universal selector
attribute selectors
:hover and :focus pseudo-classes
:target pseudo-class
:lang() pseudo-class
all UI element states pseudo-classes
all structural pseudo-classes
negation pseudo-class
::before and ::after pseudo-elements
child combinators
sibling combinators

namespaces

Extra constraints only one class selector allowed per sequence of simple selectors


Selectors profile
Specification CSS level 2
Accepts type selectors
universal selector
attribute presence and values selectors
class selectors
ID selectors
:link, :visited, :active, :hover, :focus, :lang() and :first-child pseudo-classes
descendant combinator
child combinator
adjacent sibling combinator
::first-line and ::first-letter pseudo-elements
::before and ::after pseudo-elements
Excludes

substring matching attribute selectors
:target pseudo-classes
all UI element states pseudo-classes
all structural pseudo-classes other than :first-child
negation pseudo-class
general sibling combinators

namespaces

Extra constraints more than one class selector per sequence of simple selectors (CSS1 constraint) allowed

CSS에서 셀렉터는 문서 트리 내 요소에 어떤 스타일 규칙을 적용할 지 결정하는 패턴 매치 규칙을 표현합니다.

In CSS, selectors express pattern matching rules that determine which style rules apply to elements in the document tree.

아래 셀렉터 (CSS 레벨 2)는 h1 안의 a 요소 중 name 속성이 지정된 것 모두에 매치합니다.

The following selector (CSS level 2) will match all anchors a with attribute name set inside a section 1 header h1:

h1 a[name]

이 셀렉터에 주어져 있는 모든 CSS 선언이 셀렉터에 매치한 요소에 적용할 것입니다.

All CSS declarations attached to such a selector are applied to elements matching it.

Selectors profile
Specification STTS 3
Accepts

type selectors
universal selectors
attribute selectors
class selectors
ID selectors
all structural pseudo-classes
all combinators

namespaces

Excludes non-accepted pseudo-classes
pseudo-elements
Extra constraints some selectors and combinators are not allowed in fragment descriptions on the right side of STTS declarations.

STTS3에 있어 셀렉터에는 2개의 다른 이용법이 있습니다.

Selectors can be used in STTS 3 in two different manners:

  1. CSS의 선택 메카니즘과 동일한 선택 메카니즘. 선언이 어떤 셀렉터에 주어졌을 때, 그 셀렉터에 매치하는 요소에 선언이 적용됩니다.
    a selection mechanism equivalent to CSS selection mechanism: declarations attached to a given selector are applied to elements matching that selector,
  2. 선언 우측에 나타나는 기법
    fragment descriptions that appear on the right side of declarations.

12. 적합성과 요건

이 섹션은 셀렉터 스펙의 적합성을 정의합니다.

This section defines conformance with the present specification only.

UA가 디바이스의 제약으로 인해 이 스펙의 일부를 구현하지 못하더라도, 그를 부적합하다 간주하지 않습니다. 예를 들어, 인터렉티브하지 못한 UA는 동적 의사 클래스를 구현하지 못할 것입니다.

The inability of a user agent to implement part of this specification due to the limitations of a particular device (e.g., non interactive user agents will probably not implement dynamic pseudo-classes because they make no sense without interactivity) does not imply non-conformance.

셀렉터 스펙을 이용하는 모든 스펙은 프로필을 정의하여 허용하는 셀렉터와 제외하는 셀렉터, 스펙 상의 제약을 작성해야 합니다.

All specifications reusing Selectors must contain a Profile listing the subset of Selectors it accepts or excludes, and describing the constraints it adds to the current specification.

파싱 에러에 따라 셀렉터는 invalid가 됩니다. 이해 불가능한 토큰이나 허용하지 않는 파싱 포인트가 있는 경우에 파싱에러를 일으킵니다.

Invalidity is caused by a parsing error, e.g. an unrecognized token or a token which is not allowed at the current parsing point.

유저 에이전트의 구문 파싱 에러의 처리에 있어, 다음 사항에 주목해야합니다.

User agents must observe the rules for handling parsing errors:

셀렉터를 이용하는 스펙은 어떻게 파싱 에러를 저리할 지 정의해야 합니다. (CSS같은 경우, 해당 셀렉터에 정의된 규칙 모두를 드롭합니다)

Specifications reusing Selectors must define how to handle parsing errors. (In the case of CSS, the entire rule in which the selector is used is dropped.)

13. Tests

This specification has a test suite allowing user agents to verify their basic conformance to the specification. This test suite does not pretend to be exhaustive and does not cover all possible combined cases of Selectors.

14. Acknowledgements

The CSS working group would like to thank everyone who has sent comments on this specification over the years.

In particular, the working group would like to extend special thanks to Donna McManus, Justin Baker, Joel Sklar, and Molly Ives Brower who performed the final editorial review of the last call draft. The working group would also like to thank Adam Kuehn, Boris Zbarsky, David Perrell, Elliotte Harold, Matthew Raymond, Ruud Steltenpool, Patrick Garies, Anton Prowse, and the W3C Internationalization Working Group for their last call comments and kind words.

15. 참고 문서

15.1. 표준 참고 문서

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 07 June 2011. W3C Recommendation. URL: http://www.w3.org/TR/2011/REC-CSS2-20110607/
[CSS3NAMESPACE]
Elika J. Etemad; Anne van Kesteren. CSS Namespaces Module. 29 September 2011. W3C Recommendation. URL: http://www.w3.org/TR/2011/REC-css3-namespace-20110929/
[FLEX]
Flex: The Lexical Scanner Generator. Version 2.3.7, ISBN 1882114213
[UNICODE]
The Unicode Consortium. The Unicode Standard, Version 6.0.0, (Mountain View, CA: The Unicode Consortium, 2011. ISBN 978-1-936213-01-6) and as updated from time to time by the publication of new versions. (See http://www.unicode.org/unicode/standard/versions/ for the latest version and additional information on versions of the standard and of the Unicode Character Database).
Available at http://www.unicode.org/versions/Unicode6.0.0/
[YACC]
S. C. Johnson. YACC - Yet another compiler compiler. Murray Hill. 1975. Technical Report.

15.2. 정보 참고 문서

[BCP47]
A. Phillips; M. DavisTags for Identifying Languages and Matching of Language Tags. September 2009. Internet Best Current Practice 47. URL: http://www.rfc-editor.org/rfc/bcp/bcp47.txt
[CSS1]
Håkon Wium Lie; Bert Bos. Cascading Style Sheets (CSS1) Level 1 Specification. 11 April 2008. W3C Recommendation. URL: http://www.w3.org/TR/2008/REC-CSS1-20080411
[DOM-LEVEL-3-CORE]
Gavin Nicol; et al. Document Object Model (DOM) Level 3 Core Specification. 7 April 2004. W3C Recommendation. URL: http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407
[HTML401]
David Raggett; Ian Jacobs; Arnaud Le Hors. HTML 4.01 Specification. 24 December 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[MATHML]
Patrick Ion; Robert Miner. Mathematical Markup Language (MathML) 1.01 Specification. 7 July 1999. W3C Recommendation. URL: http://www.w3.org/1999/07/REC-MathML-19990707
[STTS3]
Daniel Glazman. Simple Tree Transformation Sheets 3. Electricité de France. 11 November 1998. Submission to the W3C. URL: http://www.w3.org/TR/NOTE-STTS3
[SVG11]
Erik Dahlström et. al. Scalable Vector Graphics (SVG) 1.1 Specification. 16 August 2011. W3C Recommendation. URL: http://www.w3.org/TR/2011/REC-SVG11-20110816/
[UAX29]
Mark Davis. Text Boundaries. 25 March 2005. Unicode Standard Annex #29. URL: http://www.unicode.org/unicode/reports/tr29/tr29-9.html
[XML-NAMES]
Tim Bray; et al. Namespaces in XML 1.0 (Third Edition). 6 August 2009. W3C Proposed Edited Recommendation. URL: http://www.w3.org/TR/2009/PER-xml-names-20090806
[XML10]
C. M. Sperberg-McQueen; et al. Extensible Markup Language (XML) 1.0 (Fifth Edition). 10 February 1998. W3C Proposed Edited Recommendation. Revised 5 February 2008 URL: http://www.w3.org/TR/2008/PER-xml-20080205