CSS Selectors: How to Target HTML for Styling

CSS selectors are like addresses for your HTML, telling the browser which elements to style. They're used to apply everything from colors to layouts. The main footgun is specificity: an overly specific selector can be difficult to override later.
WHY IT EXISTS HTML provides a document's structure, but has no inherent styling. CSS was created to separate presentation from content. Selectors are the bridge between them, providing the mechanism to connect a CSS style rule (the "what") to a specific HTML element (the "where").
THE MENTAL MODEL Think of CSS selectors as a query language for the DOM (Document Object Model). Just as you query a database to find specific records, you use selectors to find specific HTML elements. A simple query might be "find all paragraphs" (p), while a more complex one could be "find all links inside the main navigation that are currently being hovered over."
HOW IT WORKS The browser parses HTML into a tree of elements. For each rule in your stylesheet, it uses the selector to find all matching elements in that tree. Once matched, the browser applies the styles. Key selector types include: Type selectors (p, h1) to target elements by tag name; Class selectors (.card, .btn-primary) to target elements by their class attribute; and ID selectors (#main-header) to target a single, unique element.
WHEN TO USE IT You use selectors in every CSS rule you write; they are fundamental to styling. Use class selectors for reusable components like buttons or alerts. Use ID selectors for unique page landmarks like a main header or footer. Use type selectors for applying broad, default styles across your site.
WHEN NOT TO USE IT Avoid over-relying on ID selectors for styling. Their high specificity makes them difficult to override and reduces reusability. Also, avoid long, complex selector chains like div#app .sidebar ul li a. These are brittle—a small change in HTML structure breaks the style—and their high specificity leads to maintenance headaches. Prefer simple, class-based selectors.
ONE CANONICAL EXAMPLE To style a primary action button, you first add a class to the HTML: <button class="btn-primary">Submit</button>. Then, in your CSS, you use a class selector to target it: .btn-primary { background-color: blue; color: white; border-radius: 4px; }. This rule now applies to any element given the btn-primary class, making the style reusable and independent of its location in the markup.
Read the original → developer.mozilla.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.