CSS Class Selector (.class) - Complete Guide

Master the CSS class selector for styling elements by class name. Learn syntax, multiple classes, specificity, and best practices for scalable CSS architecture.

Basic Selectors

Detailed Explanation

The CSS Class Selector

The class selector is the workhorse of CSS. It matches elements that have a specific class attribute value, and it is the most commonly used selector in production stylesheets.

Syntax

.classname {
  /* styles */
}

The dot (.) prefix distinguishes class selectors from type selectors. The class name must match the value in the HTML class attribute exactly (case-sensitive).

Multiple Classes on One Element

HTML elements can have multiple classes separated by spaces:

<button class="btn btn-primary btn-large">Submit</button>

You can target elements with multiple classes by chaining selectors:

.btn.btn-primary {
  background: blue;
  color: white;
}

This matches elements that have both btn and btn-primary classes. The specificity of chained classes is additive: .btn.btn-primary has specificity (0, 2, 0).

Specificity

A single class selector has specificity (0, 1, 0). This makes it more specific than any number of type selectors but less specific than a single ID selector.

/* Specificity: (0, 1, 0) — wins over p { } */
.intro { color: blue; }

/* Specificity: (0, 0, 1) — loses to .intro */
p { color: red; }

Best Practices

  • Prefer classes over IDs for styling. Classes are reusable; IDs are not.
  • Use meaningful names that describe the role, not the appearance: .error-message instead of .red-text.
  • Follow a naming convention like BEM (.block__element--modifier), SMACSS, or utility-first (Tailwind).
  • Avoid overly generic names like .container or .wrapper that may conflict across components.

Use Case

Class selectors are used in virtually every CSS stylesheet. They power component-based architectures (BEM, CSS Modules), utility frameworks (Tailwind CSS), and JavaScript-driven class toggling for interactive states. Understanding class selectors deeply is fundamental to writing maintainable CSS at any scale.

Try It — CSS Selector Reference

Open full tool