How to Use Class Selector in CSS: Simple Guide
Use the
class selector in CSS by prefixing a class name with a dot (.). This selector targets all HTML elements with that class attribute, allowing you to apply styles to them.Syntax
The class selector in CSS starts with a dot (.) followed by the class name. It selects all elements that have that class attribute.
- Dot (
.): Indicates a class selector. - Class name: Matches the
classattribute value in HTML. - Declaration block: Contains CSS properties and values to style the selected elements.
css
.classname {
property: value;
}Example
This example shows how to style all elements with the class highlight to have a yellow background and bold text.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Class Selector Example</title> <style> .highlight { background-color: yellow; font-weight: bold; padding: 5px; } </style> </head> <body> <p>This is a normal paragraph.</p> <p class="highlight">This paragraph is highlighted with the class selector.</p> <div class="highlight">This div also uses the same class styling.</div> </body> </html>
Output
A webpage with one normal paragraph and two elements (a paragraph and a div) with yellow background and bold text.
Common Pitfalls
Common mistakes when using class selectors include:
- Forgetting the dot (
.) before the class name in CSS, which makes the selector invalid. - Using class names in CSS that don’t match the HTML exactly (case-sensitive).
- Applying styles to elements without adding the class attribute in HTML.
- Confusing class selectors with ID selectors, which use
#instead of..
css
/* Wrong: missing dot before class name */ highlight { color: red; } /* Correct: dot before class name */ .highlight { color: red; }
Quick Reference
Remember these quick tips when using class selectors:
- Always start with a dot (
.) in CSS. - Class names are case-sensitive and must match HTML exactly.
- Multiple elements can share the same class.
- You can combine class selectors with other selectors for more specific styling.
Key Takeaways
Use a dot (.) before the class name in CSS to select elements by class.
Class selectors apply styles to all HTML elements with that class attribute.
Class names in CSS must exactly match the HTML class attribute (case-sensitive).
Forget the dot and your CSS won’t apply to the class elements.
Multiple elements can share the same class to get the same styles.