CSS combinators explain the relationship between two selectors, allowing you to select elements based on their exact structural position inside the HTML DOM tree.
CSS supports four combinator operators:
/* 1. Descendant Selector (space) */
div p { color: #f8fafc; }
/* 2. Direct Child Selector (>) */
div > p { color: #38bdf8; }
/* 3. Adjacent Sibling Selector (+) */
h2 + p { font-size: 1.1rem; }
/* 4. General Sibling Selector (~) */
h2 ~ p { color: #94a3b8; }
Combinator types explained:
A B): Matches all B elements nested anywhere inside A (children, grandchildren, etc.).A > B): Matches only B elements that are direct children of A.A + B): Matches element B that is placed immediately after A as a direct sibling.A ~ B): Matches all B elements that follow A as siblings.flowchart TD
A["A B (Descendant: All nested children)"]
B["A > B (Direct Child: Only immediate 1st level children)"]
C["A + B (Adjacent Sibling: Immediate next sibling)"]
D["A ~ B (General Sibling: All following siblings)"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Combinators Demonstration</title>
<style>
.container {
background-color: #1e293b;
padding: 1.5rem;
border-radius: 8px;
}
/* Target paragraph immediately following h3 */
h3 + p {
color: #38bdf8;
font-weight: bold;
}
/* Target direct li children of .menu */
ul.menu > li {
display: inline-block;
margin-right: 1rem;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<div class="container">
<h3>Combinator Header</h3>
<p>This paragraph is an adjacent sibling (h3 + p) and gets highlighted in blue!</p>
<p>This paragraph is a general sibling.</p>
</div>
</body>
</html>
> direct child selectors to scope styles: Prevents top-level navigation styles from accidentally cascading down into nested sub-menus.h2 + p for intro paragraph styling: Perfect for styling the lead paragraph immediately following an article heading.div > ul > li > a > span) to maintain manageable CSS specificity.Write a CSS rule targeting a paragraph immediately following an h2 heading (h2 + p) that sets font-size: 1.2rem;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.