Selectors and specificity
Artifact: A working mental model of which rule wins
1. Principle
A CSS rule has two parts:
selector {
property: value;
}
The selector says what to target. The properties say what to change.
Five selectors you will use 95% of the time:
| Selector | Targets | Example |
|---|---|---|
h1 | All <h1> elements (type selector) | h1 { color: red; } |
.intro | All elements with class="intro" | .intro { font-size: 20px; } |
#contact | The element with id="contact" | #contact { background: blue; } |
nav a | All <a> inside <nav> (descendant) | nav a { color: white; } |
a:hover | Links being hovered (pseudo-class) | a:hover { underline; } |
When two rules touch the same element, the more specific one wins. The hierarchy:
- Inline styles (
style="...") — never used. #idselectors — most specific selectors..class, attribute, and pseudo-class selectors.tagnameselectors — least specific.
If two rules have the same specificity, the later one wins. CSS = "Cascading Style Sheets" — the cascade is real.
2. Do (you try)
Replace your styles.css with this:
/* type selector — every h1 */
h1 {
color: navy;
}
/* class selector — anything with class="lead" */
.lead {
font-size: 1.2rem;
font-weight: 600;
}
/* descendant selector — links inside nav */
nav a {
text-decoration: none;
color: navy;
}
/* pseudo-class — hovered links */
nav a:hover {
text-decoration: underline;
}In your index.html, find the first paragraph (the one-sentence intro under your h1) and add a class:
<h1>Your Name</h1>
<p class="lead">One sentence about who you are.</p>Save both. Refresh.
3. Verify (how you know)
Three checks:
- Your h1 is now navy, larger than default browser blue.
- Your lead paragraph (the one with
class="lead") is bigger and bolder than the others. - Nav links are navy with no underline. Hover over one — underline appears.
The prediction quiz. Add this rule to the end of styles.css:
p {
color: gray;
}
.lead {
color: red;
}Predict before refreshing: what color is the lead paragraph?
- (a) gray, because
pcomes second... no,.leadcomes second. - (b) red, because
.leadhas higher specificity thanp. - (c) red, because
.leadcomes later anyway.
The answer is red, and both (b) and (c) are valid reasons. .lead beats p on specificity and comes later.
Now refresh and confirm.
4. Reference
Locked. Try it yourself first.