Episode 16 of 53
Adjacent Selectors in CSS
Learn the adjacent sibling combinator (+) to target elements immediately after another.
The adjacent sibling selector uses the + symbol to target an element that comes immediately after another element, at the same nesting level.
Syntax
/* Target a <p> that comes right after an <h2> */
h2 + p {
font-size: 1.2rem;
color: #555;
margin-top: 0;
}
How It Works
<h2>Section Title</h2>
<p>This paragraph IS matched (immediately after h2)</p>
<p>This paragraph is NOT matched</p>
Only the first <p> right after the <h2> is selected.
General Sibling Selector (~)
If you want to target all siblings (not just the adjacent one), use the ~ combinator:
/* Target ALL <p> elements that come after an <h2> */
h2 ~ p {
color: #666;
}
Practical Uses
- Styling the first paragraph after headings differently
- Adding space between specific element combinations
- Creating visual relationships between adjacent elements
/* Add extra spacing between consecutive cards */
.card + .card {
margin-top: 1.5rem;
}