Selector

The W3C states that “A selector represents a structure. This structure can be understood for instance as a condition that determines which elements in the document tree are matched by this selector, or as a flat description of the HTML or XML fragment corresponding to that structure.”
Examples of selectors:
  • H3
  • P.footer
  • TABLE#bigtable > TR
  • TABLE#bigtable TD
  • node
  • node[x="2"]
  • node:selected
  • node#subgraph1 > #id2
A selector is composed of one or more simple selectors.
Examples of simple selectors:
  • H3
  • P.footer
  • TABLE#bigtable
  • TR
  • node
  • node[x="2"]
  • node:selected
  • #id2
A simple selector is made of minimal building blocks.
Examples of minimal building blocks of selectors:
  • H3
  • .footer
  • node
  • [x="2"]
  • :selected
  • #id2
When two or more simple selectors are aggregated into a selector, they are separated by combinators. A combinator is a single character which semantics is described in the following table. Extra spaces are ignored.
Combinator symbols 
Transition
Meaning
E  F
Matches an F element that is a descendant of an E element
E > F
Matches an F element that is a child of an E element
E + F
Matches an F element immediately preceded by an E element
The minimal building blocks of a selector are listed in the following table. For an explanation of the Specificity column, see Priority.
Minimal building blocks of a selector
Building Block
Matching Rule
Specificity
e
Matches any element of type e
0-0-1
#myid
Matches any element with an ID equal to myid
1-0-0
.myclass
Matches any element with class myclass
0-1-0
:myclass
Matches any element with pseudo-class myclass
0-1-0
[myattr]
Matches any element with the myattr attribute that exists and <> null
0-1-0
[myattr=”warning”]
Matches any element whose myattr attribute value is exactly equal to warning
0-1-0
[myattr~=”warning”]
Matches any element whose myattr attribute value is a list of space-separated values, one of which is exactly equal to warning
0-1-0
*
Matches any element
0-0-0
For example, the following line:
P.pastoral.marine { color : green ; size : 10pt ; }
matches <P class="pastoral marine old"> , sets the color of the paragraph to green , and sets the font size to 10 .
All rules start and end with an implicit “ * ” pattern. This means that a selector can match anywhere inside the hierarchy.