Selectors & Specificity
How CSS finds HTML elements on your page, and the mathematical formula the browser uses to decide which rule wins when styles collide.
The Postal Delivery Analogy
Imagine a courier trying to deliver mail on a university campus. How the envelope is addressed dictates who gets it and how precise the instruction is:
Element Selector (`p`, `div`)
Address: "To all students in Hostel 4". Everyone gets a copy. Very broad, easily overridden by more specific mail.
Class Selector (`.lead`, `.btn`)
Address: "To students wearing the Robotics Club badge". Targets any student carrying this reusable label.
ID Selector (`#student-42`)
Address: "Student ID: CS-2026-042". Exactly one individual on campus. Outranks any number of club badges!
Inline Style (`style="..."`)
Address: The Dean personally walks up to the student's desk and hands over the letter. Overrides all mailbox rules!
Anatomy of a CSS Rule
Before diving into combinators, understand the four parts that make up every single CSS rule:
"Who?" Matches the HTML element(s) in the DOM tree.
"What?" The visual feature being modified (color, margin, width).
"How?" The exact setting applied to that property.
A pair of property: value; terminated by a semicolon.
Mastering the Basic Selectors
Click any selector family below to see how it works, its specificity value, and concrete examples:
Type (Element) Selectors: `h1`, `p`, `button`, `ul`
Specificity: (0, 0, 0, 1)Targets elements based directly on their HTML tag name. Because it affects every single tag of that kind on the whole website, it should only be used for base typographic resets and document defaults.
- Setting base font sizes on
htmlandbody. - Removing margin defaults on
h1, h2, h3. - Removing list bullet padding on
ul, ol.
The 4 Combinators: Navigating the DOM Family Tree
How do you style an element based on its parent, sibling, or ancestor? Combinators describe relationships between multiple selectors:
Descendant Combinator: `div p` (Separated by space)
Matches Any Nesting DepthMatches every <p> that is inside a <div>, whether it is a child, grandchild, or 10 levels deep inside another container.
The Colon Rule: Single `:` vs Double `::`
This is one of the most common interview and exam questions for 1st-year students:
Describes a State or Dynamic Condition
Styles an existing HTML element when it is in a particular user interaction state or structural position.
:hover — Cursor hovering over element:focus-visible — Keyboard focused (Tab key):nth-child(even) — Every second item:not(.disabled) — Negation filterCreates or Targets a Sub-Part of the Element
Creates a virtual piece of the DOM that does not exist in your HTML markup, or targets specific internal parts.
::before — Injected child before content::after — Injected child after content::placeholder — Input ghost text::selection — Highlighted user textThe 4-Slot Specificity Tuple: (A, B, C, D)
The browser uses a 4-slot comparison vector (A, B, C, D) to resolve conflicts. The comparison starts from the leftmost column (A). If A is tied, it checks B, then C, then D.
| Slot | Category | What Counts | Example Selector | Points |
|---|---|---|---|---|
| A | Inline Styles | Written in HTML style="..." | <div style="color:red"> | (1, 0, 0, 0) |
| B | IDs | HTML IDs with hash #id | #main-header | (0, 1, 0, 0) |
| C | Classes, Attributes, Pseudo-classes | .class, [type], :hover | .btn:hover[disabled] | (0, 0, 3, 0) |
| D | Elements & Pseudo-elements | HTML tags p, div, ::before | p::first-line | (0, 0, 0, 2) |
| - | Universal & Combinators | *, >, +, ~, :where() | * or div > p | (0, 0, 0, 0) |
Many 1st-year students mistakenly think of (0, 1, 0, 0) as 100 and (0, 0, 1, 0) as 10, believing that 11 classes (110) will beat 1 ID (100). That is 100% false! The columns are compared independently. 1 ID (0, 1, 0, 0) will always beat 1,000 Classes (0, 0, 1000, 0)!
Which Rule Wins? (Interactive Quiz)
Round 1 of 4Put your skills to the test! Inspect the HTML and pick the rule that wins the clash:
Which rule will style the color of this introductory paragraph?
<p id="intro" class="lead text-highlight">Welcome to CSS!</p>
Test ANY Selector in Real-Time
Type any CSS selector below or click one of the presets to see its exact mathematical breakdown:
(Inline, IDs, Classes/Attrs/Pseudos, Elements)Interactive Selector Target Sandbox
Use the live visualizer below to see which HTML nodes get matched in real-time and copy the exact CSS rule:
Selectors & Specificity
Pick a selector to highlight matched nodes and see its specificity tuple.
Hero title
A subtitle under the hero.
This is a card title
- Item one
- Item two
- Item three
<section class="hero">
<h3 class="title">Hero title</h3>
<p class="subtitle">A subtitle under the hero.</p>
<button id="cta" class="btn">Call to action</button>
</section>
<section class="card">
<div class="badge">badge</div>
<p class="title">This is a card title</p>
<ul class="list">
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>
<nav class="nav">
<a href="#">Link A</a>
<a href="#">Link B</a>
</nav>
</section>5 Classic 1st-Year Traps (And How to Avoid Them)
`.btn.primary` vs `.btn .primary`
.btn.primary (no space) means the same element must have BOTH classes..btn .primary (with a space) means an element with class .primary is nested inside an element with class .btn!
`p:first-child` does NOT mean "first paragraph"!
It means: "The element is a paragraph AND it is the very first child of its parent". If your container starts with an <h1>, p:first-child matches NOTHING!
Fix: Use p:first-of-type instead!
`body div#app main.container div.card p`
Writing deep selector chains makes your styles brittle. If someone wraps the card in a <section>, your styling breaks!
Fix: Use a single class like .card__text (BEM methodology).
Block__Element--Modifier
BEM names elements with single classes:.card (Block).card__title (Element).card__title--featured (Modifier)
Every rule stays at a clean, predictable (0, 0, 1, 0), completely eradicating specificity wars!
2. Cascade & Inheritance
How browsers calculate computed values, CSS inheritance rules, and cascade layers (@layer).