Siblings are elements that share the same parent. Two selectors let you style an element based on what comes before it.
Adjacent sibling: +
h2 + p matches a paragraph that comes immediately after an h2.
<style>
h2 + p {
font-size: 1.2em;
color: #1a5276;
}
</style>
<h2>Heading</h2>
<p>This is the first paragraph after the heading. It is styled.</p>
<p>This second paragraph is not.</p>
General sibling: ~
h2 ~ p matches every paragraph that follows the h2 at the same level, not just the first.
<style>
h2 ~ p {
border-left: 3px solid #d94a00;
padding-left: 10px;
}
</style>
<p>Before the heading: not matched.</p>
<h2>Heading</h2>
<p>After the heading: matched.</p>
<p>Also matched.</p>
Where this is handy
- Add space only between neighbours:
li + li { margin-top: 8px; }leaves the first item alone. - Style a form field’s message when the input is invalid, using the input as the starting point.
- Show or hide something after a checkbox.
CSS only looks forward
:has() in Not, Is and Other Handy Selectors.