Retour au cours

Lesson 9: Core Selectors: ID Selectors (#)

**La Maîtrise de CSS : De zéro à expert en 100 leçons** *(Alternative, slightly punchier version using a common French idiomatic structure for full coverage: CSS : Maîtrisez l'essentiel en 100 leçons, but the first option is closer to the original progression.)*

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

  1. HTML: Add the id attribute to a single element. html

    My Website

  2. 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

FeatureClass Selector (.)ID Selector (#)
UsageUsed many times on a pageUsed exactly once per page
PurposeStyling reusable componentsTargeting highly specific, unique elements (often for JS/Accessibility)
SpecificityLow/MediumVery 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).