Class Selector (CSS selector)
Example
The following selector will match all
p elements with a class
attribute that contains the value
"intro":
p.intro {
⋮ declarations
}
Description
Selecting elements on the
basis of their class names is a very common technique in CSS. The
attribute selector syntax [class~="warning"] is
rather awkward, but thankfully there’s a simpler and shorter form for it:
the class selector.
Here’s a simple example that selects all
elements with a class attribute that contains the
value "warning":
.warning {
⋮ declarations
}
This example also illustrates the use of an implied universal
selector—it’s equivalent to *.warning. Note
that whitespace characters can’t appear after the period, or between an
element type selector, or explicit universal selector, and the period. For
example, the following selector will match all p
elements with a class attribute that contains the
value "warning":
p.warning {
⋮ declarations
}
A simple selector may contain more than one attribute selector and/or class selector; in such cases, the selector pattern matches elements whose attributes contain all the specified components. Here’s an example:
div.foo.bar {
⋮ declarations
}
div.foo.bar[title^="Help"] {
⋮ declarations
}
The first example selector above matches div
elements whose class attribute value contains both
the words "foo" and "bar". The
second example selector matches div elements whose
class attribute values contains both the words
"foo" and "bar", and whose
title attribute values begin with the string
"Help".
Compatibility
| IE | 5.5 | Buggy |
|---|---|---|
| 6.0 | Buggy | |
| 7.0 | Full | |
| Firefox | 1.0 | Full |
| 1.5 | Full | |
| 2.0 | Full | |
| Safari | 1.3 | Full |
| 2.0 | Full | |
| 3.0 | Full | |
| Opera | 9.2 | Full |
| 9.5 | Full |
In Internet Explorer 6, the class selector doesn’t work if the class name starts with a hyphen or an underscore.
In Internet Explorer up to and including version
6, only the last class selector is honored; all others in a chain of class
selectors are ignored. For example, a selector like
.x.y.z will match all elements with a
class attribute that contains the value
"z", but will not restrict the match to elements that
also have the class attribute values
"x" and "y", which it should.
In Internet Explorer versions up to and including 6, if an ID selector that’s combined with a class selector is unmatched, all subsequent ID selectors that use the same ID and are combined with a class selector, are also treated as unmatched.
User-contributed notes
There are no comments yet.
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.

