CSS - Combinators

Overview

Estimated time: 10 minutes

Combinators relate elements to each other so you can target structures like children and siblings.

Learning Objectives

  • Use descendant, child, adjacent sibling, and general sibling combinators.
  • Know when to prefer child over descendant for performance and clarity.

Details & Examples

  • Descendant: article p
  • Child: ul > li
  • Adjacent sibling: h2 + p
  • General sibling: h2 ~ p

Combinators

Descendant selector colored.

Another descendant paragraph.

  • Child list item
  • Child list item

Adjacent sibling of h3 is italic.

General sibling also affected and indented.

Common Pitfalls

  • Overly broad descendant selectors can be slow and fragile; prefer child when possible.

Checks for Understanding

  1. What selector matches the first paragraph after an h2?
Show answers
  1. h2 + p (adjacent sibling)

Exercises

  1. Convert a broad descendant selector to a child selector for clarity.
  2. Use adjacent sibling to style only the first paragraph after an h2.
Suggested answers
  1. Change ul li to ul > li when you need direct children.
  2. h2 + p targets only the immediate following paragraph.