CSS Adjacent Sibling Selector (A + B) — Immediately Following Element
Learn the CSS adjacent sibling combinator (+) that targets an element immediately following another sibling. Great for spacing, typography, and conditional styling patterns.
Detailed Explanation
CSS Adjacent Sibling Selector
The adjacent sibling combinator (+) selects an element that is the immediate next sibling of another element. Both elements must share the same parent.
Syntax
/* Add top margin to any <p> that directly follows an <h2> */
h2 + p {
margin-top: 0.5rem;
font-size: 1.1rem;
}
How It Works
<div>
<h2>Title</h2>
<p>First paragraph</p> <!-- matched by h2 + p -->
<p>Second paragraph</p> <!-- NOT matched (not adjacent to h2) -->
</div>
The key rule: the target element must immediately follow the reference element with no other element siblings in between.
Common Use Cases
Lobotomized Owl (* + *):
/* Add vertical spacing between any adjacent siblings */
.stack > * + * {
margin-top: 1rem;
}
Typography refinement:
/* Remove top margin when heading follows heading */
h2 + h3 { margin-top: 0; }
/* Style the first paragraph after a heading */
h1 + p { font-size: 1.25rem; font-weight: 300; }
Form patterns:
/* Show error message only when it follows an invalid input */
input:invalid + .error-msg { display: block; }
Specificity
The sum of both parts: h2 + p = (0, 0, 2).
Use Case
Adjacent sibling selectors are widely used in typography systems for controlling spacing between different heading levels and paragraphs. The 'lobotomized owl' pattern (> * + *) is a popular spacing technique in modern CSS. Form validation patterns use it to show error messages after invalid inputs. Content management systems use it to handle spacing between different content blocks.