2.1free~18 min

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:

SelectorTargetsExample
h1All <h1> elements (type selector)h1 { color: red; }
.introAll elements with class="intro".intro { font-size: 20px; }
#contactThe element with id="contact"#contact { background: blue; }
nav aAll <a> inside <nav> (descendant)nav a { color: white; }
a:hoverLinks being hovered (pseudo-class)a:hover { underline; }

When two rules touch the same element, the more specific one wins. The hierarchy:

  1. Inline styles (style="...") — never used.
  2. #id selectors — most specific selectors.
  3. .class, attribute, and pseudo-class selectors.
  4. tagname selectors — 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:

cssstyles.css
/* 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:

htmlindex.html — excerpt
<h1>Your Name</h1>
<p class="lead">One sentence about who you are.</p>

Save both. Refresh.

3. Verify (how you know)

Three checks:

  1. Your h1 is now navy, larger than default browser blue.
  2. Your lead paragraph (the one with class="lead") is bigger and bolder than the others.
  3. Nav links are navy with no underline. Hover over one — underline appears.

The prediction quiz. Add this rule to the end of styles.css:

cssadd to styles.css
p {
color: gray;
}

.lead {
color: red;
}

Predict before refreshing: what color is the lead paragraph?

  • (a) gray, because p comes second... no, .lead comes second.
  • (b) red, because .lead has higher specificity than p.
  • (c) red, because .lead comes 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.