How to Use Adjacent Sibling Selector in CSS: Simple Guide
The CSS adjacent sibling selector
+ targets an element that is immediately after another element at the same level. Use it like element1 + element2 to style element2 only if it directly follows element1.Syntax
The adjacent sibling selector uses the + symbol between two selectors. It selects the second element only if it comes immediately after the first element, and both share the same parent.
element1: The first element.+: The adjacent sibling combinator.element2: The element immediately followingelement1.
css
element1 + element2 {
/* CSS rules here */
}Example
This example changes the color of a paragraph only if it comes immediately after a heading.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Adjacent Sibling Selector Example</title> <style> h1 + p { color: green; font-weight: bold; } </style> </head> <body> <h1>Title</h1> <p>This paragraph is green and bold because it follows the h1 directly.</p> <p>This paragraph is normal because it does not immediately follow an h1.</p> <h1>Another Title</h1> <div></div> <p>This paragraph is normal because it does not immediately follow an h1.</p> </body> </html>
Output
A webpage with the first paragraph below the first heading in green and bold text. The second paragraph and the paragraph after the div remain normal black text.
Common Pitfalls
One common mistake is expecting the selector to style all siblings after the first element, but it only styles the immediate next sibling. Also, the two elements must share the same parent; otherwise, the selector won't work.
Incorrect example:
h1 + p {
color: red;
}
/* This will NOT style paragraphs that are not immediately after an h1 */Correct usage:
h1 + p {
color: red;
}Quick Reference
- Selector:
element1 + element2 - Meaning: Selects
element2immediately afterelement1. - Same parent: Both elements must share the same parent.
- Only immediate sibling: Does not select elements further down the line.
Key Takeaways
The adjacent sibling selector (+) targets only the element immediately after another at the same level.
Both elements must share the same parent for the selector to work.
It does not select all siblings, only the very next one.
Use it to style elements based on their immediate neighbor in the HTML structure.
Remember it only works forward, not backward or for non-adjacent siblings.