Selectors in depth
Target exactly the elements you want with type, class, id, group, descendant and pseudo-class selectors.
The selectors you will use every day
| Selector | Picks | Example |
|---|---|---|
| p | every <p> | p { line-height: 1.6; } |
| .card | elements with class="card" | .card { padding: 1rem; } |
| #menu | the element with id="menu" | #menu { display: flex; } |
| h1, h2 | every h1 and every h2 | h1, h2 { color: navy; } |
| nav a | links inside a nav | nav a { text-decoration: none; } |
| ul > li | li that are direct children of ul | ul > li { margin: 4px; } |
| * | every element | * { box-sizing: border-box; } |
Pseudo-classes: elements in a state
a:hover { color: #FFA500; } /* mouse over the link */
input:focus { outline: 3px solid #FFA500; } /* field being typed in */
li:first-child { font-weight: bold; } /* first item of a list */
li:nth-child(even) { background: #f5f5f5; } /* every second item */
button:disabled { opacity: .5; }
Which rule wins? (the cascade)
When two rules set the same property on the same element:
- The more specific selector wins: an id beats a class, a class beats an element name.
- If they are equally specific, the rule written later wins.
p { color: black; }
.intro { color: navy; } /* wins over p: a class is more specific */
#lead { color: orange; } /* wins over .intro: an id is more specific */
Exercise
Make every link inside the nav white, and orange when hovered.
nav a {
}
Show a possible solution
nav a {
color: #ffffff;
}
nav a:hover {
color: #FFA500;
}
Check your understanding
Quick check
Which selector picks elements with class="note"?
Why: A dot means class; a hash means id.
Quick check
"nav a" picks…
Why: A space means "inside".
Quick check
Two rules set the colour of the same element: ".intro" and "p". Which wins?
Why: A class selector is more specific than an element selector.