References

Beginner-friendly references for web development, with live, editable examples.

The CSS .class selector

Selector CSS All modern browsers Updated
Quick answer

The CSS class selector targets every element with a given class, written with a leading dot — .btn { … } styles all elements with class="btn". Classes are reusable across many elements and are the standard, recommended way to apply styles, because they keep specificity low and predictable.

Overview

The class selector is the one you will reach for more than any other. Put a class on an element, like class="card", and select it in CSS with a dot: .card { … }. Every element that shares that class gets the styles, which is what makes classes the natural unit of reuse.

An element can carry several classes at once (class="btn btn-primary"), and you can target combinations: .btn.btn-primary matches an element with both. Classes are the backbone of every methodology from BEM to utility frameworks, precisely because they are reusable and their specificity (0,1,0) is low and consistent — easy to override when you need to.

That low specificity is a feature. Compared with the ID selector, which is hard to override, classes keep your stylesheet flexible. The advice for most projects is simple: style with classes by default, and reach for other selectors only when a class does not fit.

Syntax

/* matches class="card" */
.card {
  padding: 16px;
}

/* element with BOTH classes */
.btn.btn-primary {
  background: #1c7ce9;
}

Example

Live example
<style>
  .card { background: #f5f7fb; padding: 16px 18px; border-radius: 10px; font: 15px system-ui, sans-serif; margin-bottom: 8px; }
  .card.highlight { background: #1c7ce9; color: #fff; }
</style>
<div class="card">A plain .card</div>
<div class="card highlight">A .card.highlight (both classes)</div>

Best practices

  • Make classes your default selector — they are reusable and keep specificity low and predictable.
  • Name classes by purpose (.card, .btn-primary) rather than by appearance, so the styling can change without renaming.
  • Use multiple classes on one element to compose styles, e.g. class="btn btn-primary".
  • Prefer classes over IDs for styling, since IDs are far harder to override.

Frequently asked questions

How do I select a class in CSS?
Use a dot before the class name, e.g. .card { … } styles every element with class="card".
Can an element have more than one class?
Yes. Separate them with spaces in the markup (class="btn btn-primary"), and each class can be targeted on its own or in combination.
What is the difference between a class and an ID selector?
A class (.name) is reusable across many elements and has low specificity; an ID (#name) should be unique and has high specificity that is hard to override.
How do I select an element with two specific classes?
Chain them with no space, e.g. .btn.btn-primary matches only elements that have both classes.