Lesson 4 / 28
Combinators
Combine selectors to target elements by relationship.
Four combinators
A B any descendant, A > B direct child only, A + B immediate next sibling, A ~ B any later sibling.
Combinators in CSS
Notice how the spacing between selectors changes the meaning.
nav a { color: blue; } /* any <a> inside <nav> */
ul > li { margin: 4px; } /* direct <li> children only */
h2 + p { margin-top: 0; } /* <p> right after an <h2> */
h2 ~ p { color: gray; } /* every <p> after an <h2> */Quick check: Which combinator selects only direct children?
- A B
- A > B
- A ~ B
Answer
A > B — `>` restricts the match to immediate children, not all descendants.