Skip to main content

Class Selector (CSS selector)

By Adam Roberts

HTML & CSS

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Syntax

.className {
declaration block
}

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". To clarify further the html that would match the above selectors could be as follows:

<div class="foo bar">Matches first example</div>
<div class="foo bar" title="Help">Matches second example</div>

Example

The following selector will match all p elements with a class attribute that contains the value "intro":

p.intro {
  ⋮ declarations
}

Adam is SitePoint's head of newsletters, who mainly writes Versioning, a daily newsletter covering everything new and interesting in the world of web development. He has a beard and will talk to you about beer and Star Wars, if you let him.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.