A class selector matches any element whose class attribute includes the given class name, and a single element can carry multiple classes at once, separated by spaces in the HTML, like class="card featured", combining the styling from every matching class rule. Classes carry moderate specificity, higher than a plain type selector but lower than an ID selector, and are specifically designed to be reused across as many elements as needed throughout a document, unlike an ID, which is meant to be unique.
1Understanding Class Selectors
A class selector matches any element whose class attribute includes the given class name, and a single element can carry multiple classes at once, separated by spaces in the HTML, like class="card featured", combining the styling from every matching class rule. Classes carry moderate specificity, higher than a plain type selector but lower than an ID selector, and are specifically designed to be reused across as many elements as needed throughout a document, unlike an ID, which is meant to be unique.
Design classes to be reusable across multiple elements and even multiple projects, rather than naming them after one specific instance's content or position — a class named .card is far more reusable than one named .third-box-on-homepage.
.card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
}2Practical Example
Here is a real-world application of Class Selectors showing how it is used in production CSS code.
<div class="card featured">...</div>
.card { padding: 16px; }
.featured { border: 2px solid gold; }3Best Practices
Follow these guidelines when working with Class Selectors:
1. Use classes as the primary, default way to apply styling, since they're reusable across any number of elements, unlike IDs
2. Combine multiple classes on a single element, like class="btn btn-primary", to compose styling from smaller, reusable pieces rather than duplicating declarations across many single-purpose classes
3. Name classes descriptively based on their purpose or role, like .error-message, rather than their specific visual appearance, like .red-text, which becomes misleading if the styling later changes
Tip: Design classes to be reusable across multiple elements and even multiple projects, rather than naming them after one specific instance's content or position — a class named .card is far more reusable than one named .third-box-on-homepage.
.card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
}