9. Core Selectors: ID Selectors (#)
ID selectors target a single, unique element within the HTML document. They are identified by the hash symbol (#).
Defining and Using an ID
-
HTML: Add the
idattribute to a single element. htmlMy Website
-
CSS: Target the ID by preceding the ID name with a hash (
#). css #main-header { background-color: #333; color: white; padding: 20px; }
ID vs. Class: The Crucial Difference
| Feature | Class Selector (.) | ID Selector (#) |
|---|---|---|
| Usage | Used many times on a page | Used exactly once per page |
| Purpose | Styling reusable components | Targeting highly specific, unique elements (often for JS/Accessibility) |
| Specificity | Low/Medium | Very High (Hard to override) |
Modern CSS Best Practice:
In modern web development, developers tend to rely almost exclusively on Class selectors for styling. ID selectors are often reserved for JavaScript manipulation, linking (anchor tags), or accessibility features, rather than defining cosmetic styles.
Why Avoid IDs for Styling? Because their high specificity makes stylesheets hard to manage and brittle (inflexible).