Class selectors

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

The CSS class selector matches elements based on the contents of their class attribute.

/* All elements with class="spacious" */
.spacious {
  margin: 2em;
}

/* All <li> elements with class="spacious" */
li.spacious {
  margin: 2em;
}

/* All <li> elements with a class list that includes both "spacious" and "elegant" */
/* For example, class="elegant retro spacious" */
li.spacious.elegant {
  margin: 2em;
}

Syntax

.class_name {
  /* … */
}

Note that this is equivalent to the following attribute selector:

[class~="class_name"] {
  /* … */
}

The class_name value must be a valid CSS identifier. HTML class attributes which are not valid CSS identifiers must be escaped before they can be used in class selectors.

Examples

Valid class selectors

HTML

<p class="red">This paragraph has red text.</p>
<p class="red yellow-bg">
  This paragraph has red text and a yellow background.
</p>
<p class="red fancy">This paragraph has red text and "fancy" styling.</p>
<p>This is just a regular paragraph.</p>
<!-- The next two paragraphs have class attributes
that contain characters which must be escaped in CSS -->

<p class="item?one">This paragraph has a pink background.</p>
<p class="123item">This paragraph has a yellow background.</p>

CSS

.red {
  color: #f33;
}

.yellow-bg {
  background: #ffa;
}

.fancy {
  font-weight: bold;
  text-shadow: 4px 4px 3px #77f;
}
/* In the next two rules, the class attributes must be escaped */

.item\?one {
  background-color: pink;
}

.\00003123item {
  background-color: yellow;
}

Result

Invalid class selectors

The class selectors in the following rules are not valid CSS identifiers, and will be ignored.

.item?one {
  background-color: green;
}

.123item {
  background-color: green;
}

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Opera Safari Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet WebView Android
Class_selectors 1 12 1 3.5 1 18 4 10.1 1 1.0 4.4

See also

© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors