Sibling combinators (+ and ~)
Learn + adjacent sibling and ~ general sibling combinators.
Adjacent sibling combinator: +
The + sign is the adjacent sibling combinator. It targets the element that shares the same parent and comes right after the element on the left.
Write h2 + p and you select the paragraph that comes immediately after an h2. If another tag sits between them, the match fails. This is ideal for styling the first paragraph after a heading.
General sibling combinator: ~
The ~ sign is the general sibling combinator. It targets all elements that share the same parent and come after the element on the left; other siblings may sit between them.
Write h2 ~ p and every paragraph that follows an h2 is selected. This is handy for giving the same style to all paragraphs after a heading.
What is the difference?
Both sibling combinators look at the same parent; the difference is distance. + picks only the element immediately after. ~ picks all siblings that come later.
In a menu, li + li is often used to add a separator before each list item except the first. This tiny pattern solves list separators in one line.
Exercise Reset the paragraph after a heading
Write an h2 + p selector and add margin-top: 0 inside. The paragraph right after each heading will start with no top spacing.
Show example solution
/* fix the paragraph after a heading */
h2 + p {
margin-top: 0;
}
Test yourself
-
What does h2 + p target?
h2 + p { margin-top: 0; }- All paragraphs after the h2
- The paragraph that is a direct child of h2
- The single paragraph right after the h2
- All siblings of the h2
Show answer
The single paragraph right after the h2 — Correct. The + combinator matches only the paragraph right after the h2.
-
Select the paragraph right after the h2
____ { margin-top: 0; }Show answer
h2 + p { margin-top: 0; } -
Match each combinator to its meaning
- h2 + p
- Paragraph right after the heading
- h2 ~ p
- All paragraphs after the heading
- nav > a
- Direct link inside the menu
- article p
- All paragraphs in the article