iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

CombinatorSyntaxMatches
Descendantarticle pEvery p inside an article, at any nesting depth.
Childul > liOnly lis that are a direct child of ul.
Adjacent siblingh2 + pA p that comes immediately after an h2 (same parent).
General siblingh2 ~ pEvery 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 &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Target only paragraphs that are a direct child of an article.

article p { line-height: 1.6; }

Test yourself

Q1. What does `article p` match?
Q2. What does `h2 + p` match?
Q3. Which combinator means "general sibling"?

Discussion

Loading…