Rules, selectors and the cascade
Selectors
Goal: Target elements with type, class, id, descendant, child and pseudo-class selectors · 11 min
Selectors decide which elements a rule applies to.
| selector | example | selects |
|---|---|---|
| type | p | all <p> elements |
| class | .note | elements with class="note" |
| id | #header | the element with id="header" (unique) |
| universal | * | everything |
| group | h1, h2, h3 | any of them |
| descendant | nav a | every <a> anywhere inside a <nav> |
| child | ul > li | <li> that are direct children of <ul> |
| adjacent sibling | h2 + p | the <p> right after an <h2> |
| attribute | a[href^="https"] | links whose href starts with https |
| pseudo-class | a:hover, li:first-child | an element in a certain state or position |
Combining without a space means "both at once": p.note is a <p> with class note, while p .note (with a space) is any .note inside a <p>.
Classes are the workhorse: reusable, any number per element (class="card featured"). IDs must be unique; use them rarely for styling.
Pseudo-classes worth knowing: :hover (mouse over), :focus (keyboard focus), :first-child, :last-child, :nth-child(2n) (every second one).
Worked example: Which elements are selected?
- HTML: <ul><li>A</li><li class="sale">B</li></ul>
- "li" selects A and B; ".sale" selects only B; "li:first-child" selects only A.
- "ul > li.sale" selects B: a direct child li that has class sale.
<ul>
<li>A</li>
<li class="sale">B</li>
</ul>