Skip to main content

The Class Selector

The Class Selector is the workhorse of CSS. It allows you to target a specific group of elements, regardless of their HTML tag type (like p, div, or h2), making your styles highly reusable and easy to manage.

If the Element Selector is for default, global styling, the Class Selector is for defining a distinct design component or behavior that can be applied multiple times across your page.


How to Use the Class Selector

Using a class involves two steps:

1. Assign the Class in HTML

First, you add the class attribute to one or more HTML elements. You can assign the same class to any number of elements.

index.html
<p class="warning">Error: Check your input fields.</p>
<div class="warning">Attention required.</div>
<button class="warning">Close Warning</button>

2. Select the Class in CSS

In your stylesheet, you target that class name by prefixing it with a dot (.).

styles.css
/* The dot (.) tells the browser: "Find the element with this class name." */
.warning {
border: 2px solid #ff9800; /* Amber border */
background-color: #fff3e0; /* Light orange background */
padding: 10px;
color: #e65100; /* Darker orange text */
}

Every element assigned the class warning will instantly inherit these styles.

Multiple Classes

An HTML element can have multiple classes assigned to it, separated by spaces. This is incredibly powerful for mixing and matching styles.

<button class="btn btn-primary btn-large">Save Data</button>

In your CSS, you would define these as separate, reusable rules:

/* Base button style */
.btn {
cursor: pointer;
border-radius: 4px;
}

/* Color/variant style */
.btn-primary {
background-color: blue;
color: white;
}

/* Size style */
.btn-large {
padding: 15px 30px;
}

Specificity Score

The Class Selector has a medium Specificity score. It is much more specific than an Element selector, but less specific than an ID selector.

Selector TypeSpecificity Score
Class(0, 0, 1, 0)

This score of 10 makes it the ideal selector for component styling because it's specific enough to override default element styles but low enough that you can easily override it with utility classes or more advanced selectors if needed.


Interactive Class Selector Demo

In this demo, the CSS targets the class .highlight. Notice how the div and the p tags are styled the same way because they share the class, while the regular p tag is ignored.