8. Core Selectors: Class Selectors (.)
Class selectors are the workhorses of modern CSS. They allow you to apply the same style to multiple, arbitrary elements, regardless of their HTML tag type.
Defining and Using a Class
-
HTML: Add the
classattribute to one or more elements. htmlThis is an important alert.
Another warning container.Link Button -
CSS: Target the class by preceding the class name with a dot (
.). css .warning { background-color: yellow; border: 1px solid orange; padding: 10px; }.primary-btn { background-color: darkgreen; color: white; padding: 8px 16px; border-radius: 5px; }
Key Characteristics of Classes
-
Reusability: The biggest advantage. A class can be used on any HTML element (
div,p,h1,img, etc.). -
Multiple Classes: An element can have multiple classes applied to it, separated by spaces. html
Multiple styles apply.
The browser merges the styles defined by all three classes (
text-center,warning,font-large).
Best Practice: Use descriptive, hyphenated class names (e.g., .nav-link, .card-image, .is-active).