h2 + p, using the adjacent sibling combinator +, matches a <p> element only if it comes immediately after an <h2> at the same nesting level, with nothing else in between — a classic use case being adding extra top margin only to the first paragraph directly following a heading, leaving subsequent paragraphs unaffected. h2 ~ p, using the general sibling combinator ~, instead matches every <p> that comes anywhere after that <h2> among its siblings, not just the immediately adjacent one, however many other elements separate them, as long as they share the same parent.
1Understanding Sibling Selectors
h2 + p, using the adjacent sibling combinator +, matches a <p> element only if it comes immediately after an <h2> at the same nesting level, with nothing else in between — a classic use case being adding extra top margin only to the first paragraph directly following a heading, leaving subsequent paragraphs unaffected. h2 ~ p, using the general sibling combinator ~, instead matches every <p> that comes anywhere after that <h2> among its siblings, not just the immediately adjacent one, however many other elements separate them, as long as they share the same parent.
Use the adjacent sibling combinator (+) specifically for a common pattern like removing top margin from an element only when it immediately follows another specific element, like the first paragraph right after a heading, leaving later paragraphs with their normal spacing.
h2 + p {
margin-top: 0;
}2Practical Example
Here is a real-world application of Sibling Selectors showing how it is used in production CSS code.
h2 ~ p {
color: gray;
}
<h2>Title</h2>
<p>First</p>
<p>Second</p>3Best Practices
Follow these guidelines when working with Sibling Selectors:
1. Use + (adjacent sibling) for a rule that should apply only to the very next element immediately following a specific sibling, with nothing in between
2. Use ~ (general sibling) when a rule should apply to every later sibling after a specific one, not just the immediately adjacent one
3. Remember both sibling combinators only match elements sharing the same parent — they never reach into a different nesting level or a different parent's children
Tip: Use the adjacent sibling combinator (+) specifically for a common pattern like removing top margin from an element only when it immediately follows another specific element, like the first paragraph right after a heading, leaving later paragraphs with their normal spacing.
h2 + p {
margin-top: 0;
}