CSS Class Selector
A class selector lets you target one or multiple elements that share the same class name. Think of it as creating a group of elements and saying, 'Hey CSS, style this group in the same way!'
1. How to Use a Class Selector
To use a class selector in CSS, start with a period (.
) followed by the class name. Then, define your styles inside curly braces.
CSScopy
/* Style for elements with the 'highlight' class */
.highlight {
background-color: yellow;
font-weight: bold;
}
In HTML, you can apply this style by adding theclass
attribute to any element:
HTMLcopy
<p class="highlight">This text is highlighted!</p>
2. Applying Multiple Classes
An element can have multiple classes, separated by spaces. This allows you to combine styles from different classes.
CSScopy
/* Define two classes */
.red {
color: red;
}
.bold {
font-weight: bold;
}
/* HTML with multiple classes */
<p class="red bold">This text is red and bold!</p>
Why Use Class Selectors?
Class selectors provide flexibility and reusability in your styles. They're perfect for creating consistent designs across multiple elements, without needing to repeat styles.