Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Class Selectors in CSS
You can define style rules based on the class attribute of the elements. All the elements having that class will be formatted according to the defined rule.
Basic Class Selector Syntax
Class selectors start with a dot (.) followed by the class name:
.black {
color: #808000;
}
This rule renders the content in olive color for every element with class attribute set to "black" in the document.
Element-Specific Class Selectors
You can make class selectors more specific by combining them with element selectors:
h1.black {
color: #808000;
}
This rule applies the olive color only to <h1> elements with class attribute set to "black".
Multiple Classes
You can apply multiple class selectors to a single element by separating class names with spaces:
.center {
text-align: center;
}
.bold {
font-weight: bold;
}
<style>
.center {
text-align: center;
}
.bold {
font-weight: bold;
}
.black {
color: #808000;
}
h1.black {
color: #808000;
}
</style>
<p class="center bold">
This paragraph will be styled by both center and bold classes.
</p>
<p class="black">This paragraph uses the .black selector</p>
Key Points
- Class selectors begin with a dot (.) in CSS
- Multiple elements can share the same class
- Elements can have multiple classes separated by spaces
- Combine element and class selectors for more specificity
Conclusion
Class selectors provide flexible styling by targeting elements based on their class attribute. Use multiple classes and element-specific selectors to create precise styling rules.
