The Adjacent Sibling Combinator (+) in CSS is used to select an element that immediately follows another element.
Syntax
selector1 + selector2 {
/* styles for selector2 */
}
How it works:
selector1: The preceding element.+: The adjacent sibling combinator.selector2: The element that immediately followsselector1.
Example
Let’s say we have the following HTML structure:
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<div>This is a div element.</div>
If we want to style the second paragraph differently, we can use the adjacent sibling combinator:
p + p {
color: blue;
font-weight: bold;
}
This CSS rule will only apply to the second paragraph because it immediately follows the first paragraph. The div element will not be affected.
Common Use Cases
- Styling consecutive elements:
- Creating a specific style for every other element in a list.
- Applying different styles to even and odd table rows.
- Creating specific layout effects:
- Positioning elements relative to their siblings.
- Creating unique visual effects, like alternating background colors.
Remember
- The adjacent sibling combinator only selects the immediate sibling.
- It’s often used in conjunction with other CSS selectors to create more complex styling.
By understanding and effectively using the adjacent sibling combinator, you can create more precise and visually appealing CSS styles.