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.

Know someone who'd find this guide helpful? Please share!

Page 7 of 25

Page 7 of 25

logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and so much more. Practice your skills with our free games, examples, practice questions & quizzes

    © 2024 Tomilola Group
    • facebook logo
    • twitter logo
    • instagram logo
    • linkedin logo
    • github logo
    • youtube logo