CSS Class Selector (.classname) — Selecting Elements by Class

Learn how the CSS class selector works to target elements by their class attribute. Understand specificity, multiple classes, and best practices for class naming.

Basic Selectors

Detailed Explanation

CSS Class Selector

The class selector is one of the most commonly used CSS selectors. It targets elements by their class attribute value, using a dot (.) prefix followed by the class name.

Syntax

.classname {
  /* styles */
}

How It Works

When you write .button, the browser searches the DOM for every element whose class attribute contains the word "button". Unlike ID selectors, multiple elements can share the same class, making class selectors ideal for reusable styles.

Multiple Classes on One Element

HTML elements can have multiple classes separated by spaces:

<div class="card featured highlighted">...</div>

You can target elements that have all specified classes by chaining them without spaces:

.card.featured.highlighted {
  /* matches only elements with all three classes */
}

Specificity

A single class selector has a specificity of (0, 1, 0). This is higher than element selectors (0, 0, 1) but lower than ID selectors (1, 0, 0). When two rules have the same specificity, the last one in the stylesheet wins.

Best Practices

  • Use meaningful, descriptive class names (.nav-item not .n1)
  • Follow a naming convention like BEM (.block__element--modifier)
  • Avoid overly specific selectors when a simple class will do
  • Prefer classes over IDs for styling (IDs have too-high specificity)

Use Case

Class selectors are the backbone of modern CSS architecture. Frameworks like Tailwind CSS, Bootstrap, and BEM methodology all rely heavily on class selectors. Front-end developers use them daily to style components, create reusable design tokens, and build responsive layouts. They are preferred over ID selectors because of their lower specificity and reusability across multiple elements.

Try It — CSS Selector Tester

Open full tool