Selectors
A selector comprises every part of a rule set up to—but not including—the left
curly brace {. A selector is a pattern, and
the declarations within the block
that follows the selector are applied to all the elements that match this
pattern. In the following example rule set, the selector is
h2:
h2 {
color: #666;
font-weight: bold;
}
This selector—which is comprised of a single simple selector—will match
all elements of type h2 in an HTML document. A
simple selector can either be an element type selector or the universal selector,
(*), optionally followed by attribute selectors, ID selectors, or pseudo-classes.1 A selector can
comprise a number of simple selectors separated by combinators, but it can contain only one
pseudo-element, which must be
appended to the last simple selector in the chain.
Here’s a more complex selector:
h2+p.warning:first-line {
color: #666;
font-weight: bold;
}
This selector consists of two simple selectors separated by an adjacent sibling combinator
(the + character), and a pseudo-element
(:first-line). The first simple selector
(h2) is a type selector. The second simple
selector contains a type selector (p) and an
attribute selector—in this
case, a special form of attribute selector called a class selector, which will match HTML
class attributes containing the word “warning.”
As such, the selector above would match the first line of text within
any p element that has a class
attribute value of "warning" and is an adjacent sibling
to an h2 element.
Finally, two or more selectors can be grouped, separated by commas
(,); the declaration block that follows applies to both
selectors. Consider these two rules:
#main ol {
margin-left: 2em;
}
#main ul {
margin-left: 2em;
}
They can be grouped like this:
#main ol, #main ul {
margin-left: 2em;
}
You can read about selectors in detail in the selector reference section.
Footnotes
1 Note that in CSS3, simple selectors are defined slightly differently than they are in CSS2.1. See Selector Reference for details.
User-contributed notes
- ID:
- #7
- Date:
- Sat, 23 Feb 2008 21:29:33 GMT
- Status:
- This note has not yet been confirmed for accuracy and relevance.
In front of the "ID selectors", put (#) since you have examples below "#main". Unless some one clicks on the link they will not have any idea that #main is an id selector.
Add a note
To post a note on this topic, please log in with your SitePoint username and password. If you don't have an account yet, you can create a new account for free.
