Class Selector
A CSS class selector is used to apply styles to one or more HTML elements that share the same class attribute. Unlike ID selectors that target only a single unique element, class selectors are reusable and allow multiple elements to share the same styling rules.
Key Point
- Class selectors start with a dot (.) followed by the class name.
- Can be used across multiple HTML elements.
- Elements can have multiple classes for modular styling.
- Great for reusable, flexible, and component-based styling.
- Can be combined with element names for more specific targeting.
Syntax:
.className { /* CSS properties and values */}
- .className is the name of the class you assign to HTML elements.
- Inside the curly braces {}, define the CSS styles you want applied.
Example:
<!DOCTYPE html><html>
<head> <style> .center { text-align: center; color: blueviolet; } </style></head>
<body> <h1 class="center">This heading is center-aligned.</h1></body>
</html>
Output:
.webp)
Targeting a Specific Element with a Class:
If you want to style only a particular element with a class (e.g., <p> ), you can combine the element name and class:
Example:
<!DOCTYPE html><html>
<head> <style> p.center { text-align: center; color: blue; } </style></head>
<body> <p class="center">Welcome to Quipoin</p></body>
</html>
Output:
.webp)
Tips
- Use class selectors for modular and scalable CSS.
- Combine class names for flexible and maintainable styles:
<div class="card primary-text large-padding"></div>
- Avoid using IDs for styling unless it is for a unique, one-time element.
- Write class names that are semantic and meaningful, like .btn-primary, .text-center, .card-box.