The CSS Adjacent Sibling Selector selects an element that immediately follows another element and shares the same parent. It uses the plus symbol (+) between two selectors.
This selector is useful when you want to style an element based on what appears directly before it in the HTML structure.
CSS Adjacent Sibling Selector Syntax
The syntax is:
previous-element + next-element {
property: value;
}
The first selector identifies the preceding element, while the second identifies the element immediately following it.
CSS Adjacent Sibling Selector Example
<!DOCTYPE html>
<html>
<head>
<title>Adjacent Sibling Selector</title>
<style>
h2 + p {
color: blue;
font-size: 18px;
}
</style>
</head>
<body>
<h2>CSS Tutorials</h2>
<p>This paragraph appears blue.</p>
<p>This paragraph remains unchanged.</p>
</body>
</html>
In this example, h2 + p selects the first paragraph because it immediately follows the <h2> element and shares the same parent. The second paragraph is not selected because another paragraph comes before it.
Using the Adjacent Sibling Selector with Classes
You can also combine this selector with classes to style specific elements.
<div class="card">
<h3>Web Development</h3>
<p>Learn HTML, CSS, and JavaScript.</p>
<p>Explore practical tutorials.</p>
</div>
h3 + p {
color: green;
}
The first paragraph immediately following the heading becomes green. The second paragraph remains unchanged by this rule.
Learn more about CSS Class Selectors and CSS Descendant Selectors.
Adjacent Sibling Selector vs. General Sibling Selector
The adjacent sibling selector (+) targets only the immediately following matching sibling. The general sibling selector (~) targets all matching siblings that appear later under the same parent.
For example:
h2 + p {
color: blue;
}
h2 ~ p {
font-weight: bold;
}
The first rule targets only the paragraph immediately after the heading. The second rule targets every paragraph sibling that appears after the heading.
Explore our CSS Selectors tutorial to learn more about selecting HTML elements.
When to Use the Adjacent Sibling Selector
The adjacent sibling selector is useful for styling the first paragraph after a heading, adding spacing between consecutive elements, or highlighting an element based on its immediate position in a webpage.