CSS Combinators
A combinator describes the relationship between two selectors. There are four of them, and they cover every "X relative to Y" pattern you need.
The four combinators
| Combinator | Syntax | Matches |
|---|---|---|
| Descendant | article p | Every p inside an article, at any nesting depth. |
| Child | ul > li | Only lis that are a direct child of ul. |
| Adjacent sibling | h2 + p | A p that comes immediately after an h2 (same parent). |
| General sibling | h2 ~ p | Every p after an h2 (same parent), not just the next one. |
The classic example
CSS
/* Indent only the first paragraph after a heading */
h2 + p { text-indent: 2em; }
/* Style all list items that follow the first one */
ol li ~ li { border-top: 1px solid #ddd; }
/* Match only the menu's direct list, not nested submenus */
.menu > ul > li { display: inline-block; }
Tip: Descendant (
A B) is the most lenient — it walks the whole subtree. Child (A > B) is the most precise. Reach for child whenever you don't actually need the recursion.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Combinators</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Target only paragraphs that are a direct child of an article.
article
p { line-height: 1.6; }
The child combinator.
Discussion
Loading…