Definition and Usage
The .class selector
selects all elements that have a class with the specified class name, class.
It is case-sensitive.
Placing the class name immediately after the . symbol selects all elements that have a class with that name.
For example, the .alert selector selects all elements that have a class with the specified class name, alert.
Basic Example
.alert { /* Select the alert class */
padding: 0.5em;
background-color: gold;
}
.caution { /* Select the caution class */
color: orangered;
}
<p class="alert">There is an alert message.</p>
<p>This is a paragraph element.</p>
<p class="alert caution">There is a caution message.</p>
<p>This is a paragraph element.</p>
Code Explanation
To assign multiple class names to a single element, specify multiple names separated by spaces within the class attribute value.
Note
Different elements can share the same class name.
There is an alert message.
This is a paragraph element.
There is a caution message.
This is a paragraph element.
CSS .alert selector groups and styles elements whose class name is alert. Similarly, the CSS .caution selector groups and styles elements whose class name is caution.
The element <p class="alert caution">There is a caution message.</p> has two class names: alert and caution.
Because this element matches both the .alert and .caution selectors, the styling from both selectors is applied.
Syntax
.class_name {
/* ... */
}
The syntax above is equivalent to selecting elements with the following [attribute~="value"] selector syntax.
[class~="class_name"] {
/* ... */
}
Additional Explanation
The [attribute~="value"] selector selects all elements that have a specified attribute whose value contains the word value.
The .class_name selector and the [attribute~="value"] attribute selector can select the same set of elements.
However, the .class_name selector is more explicit in expressing that it targets class names, and it offers a simpler and more concise syntax compared to the [attribute~="value"] attribute selector.
Specifications
| Specification | |
|---|---|
.class_name
|
Selectors Level 4 #class-html |
Browser Compatibility
| Selector |
Desktop Chrome
|
Desktop Edge
|
Desktop Firefox
|
Safari
|
|---|---|---|---|---|
.class_name
|
1 | 12 | 1 | 1 |