Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Selectors

The .class selector

Reference for the CSS class selector: match elements by the values in their class attribute, chain several classes, specificity, escaping rules and tips.

The class selector starts with a dot and matches every element whose class attribute contains that name as one of its space-separated values. Classes are the main tool for styling in real projects: they can be reused on any number of elements and combined freely.

Its specificity is 0,1,0, higher than any type selector but lower than an ID.

CSS
.badge {
  padding: 2px 8px;
  border-radius: 999px;
}

Try it

Combining classes

.badge.success has no space between the two classes: it matches an element that has both. .badge .success (with a space) would instead look for a .success inside a .badge.

Syntax and arguments

CSS
.name { }            /* has class "name" */
.a.b { }             /* has both classes a and b */
p.note { }           /* a <p> with class note */
.menu .item { }      /* .item inside .menu */
.sm\:flex { }        /* class "sm:flex", colon escaped */
Part Description
.name Matches when name is one of the whitespace-separated tokens in the class attribute.
Case Class names are case-sensitive in standards mode (.Card is not .card).
Valid names Must be a valid identifier. Names starting with a digit, or containing characters such as :, /, . or @, need escaping with a backslash.
Specificity 0,1,0 per class. Chaining adds up: .a.b is 0,2,0.

Usage notes

  • Reusable by design. Several elements may share a class and one element may have several. Compose small classes (.btn, .btn-primary) rather than one class per element.
  • Equivalent attribute form. .note behaves like [class~="note"], and both have specificity 0,1,0. The class selector is simply shorter and the standard choice. See attribute selectors.
  • Raise specificity cheaply. Repeating a class (.btn.btn) raises specificity. It works, but it is a smell; consider @layer or restructuring instead.
  • Naming. Choose names that describe purpose (.warning) rather than looks (.red), so the design can change without editing HTML. Conventions like BEM exist, but any consistent scheme works.
  • Dynamic classes. Toggling classes with JavaScript (element.classList.toggle("open")) is the standard way to switch styles.
  • Old browsers. A selector such as .a.b was once unreliable in very old Internet Explorer; this is no longer a practical concern.

Browser support

Supported in every browser.