The CSS Class Selector is used to style specific HTML elements that have a class attribute.
Unlike the element selector, which targets all elements of a type, the class selector allows you to apply styles to only selected elements, giving you more control and flexibility.
A class can be used multiple times on a page.
Class selectors are defined using a dot (.) followed by the class name.
.classname {
property: value;
}.highlight {
color: red;
font-size: 20px;
}👉 This will apply styles to all elements with class="highlight".
Attributes
| Property | Description | Example |
|---|---|---|
| color | Sets text color | color: blue; |
| background | Sets background color | background: yellow; |
| font-size | Sets text size | font-size: 18px; |
| padding | Adds inner spacing | padding: 10px; |
| border | Adds border | border: 1px solid black; |
Example
<!DOCTYPE html>
<html>
<head>
<title>CSS Class Selector</title>
<style>
.highlight {
color: red;
font-size: 20px;
}
.box {
background: lightgray;
padding: 10px;
border: 1px solid black;
}
</style>
</head>
<body>
<h1 class="highlight">Class Selector Example</h1>
<p class="highlight">This paragraph is highlighted.</p>
<p>This paragraph is normal.</p>
<div class="box">This is a styled box.</div>
</body>
</html>Output
Browser Output
Elements with class highlight will appear in red color with larger text
The <div> with class box will have a light gray background, padding, and border
Elements without the class will remain unchanged
Browser Support
Chrome | Firefox | Edge | Safari | Opera | IE9+ |
|---|---|---|---|---|---|
| ✅Yes | ✅Yes | ✅Yes | ✅Yes | ✅Yes | ✅Yes |
Notes
- Class selector starts with a dot (
.) - A class can be used on multiple elements
- An element can have multiple classes (e.g.,
class="box highlight") - Class names should not start with numbers
- Best practice: use meaningful and reusable class names
Conclusion
The CSS Class Selector provides flexibility and control by allowing you to style specific elements without affecting others. It is one of the most commonly used selectors in modern web development.