The General Sibling Combinator (~) is a CSS selector that matches elements that are siblings of a specified element. In simpler terms, it selects elements that share the same parent element as the specified element.
Syntax
selector1 ~ selector2 {
/* styles for selector2 */
}
How it works:
- Selector1: This is the preceding element.
- Selector2: This is the element that will be styled if it’s a sibling of
selector1.
Example
p ~ div {
background-color: yellow;
}
This rule will style all div elements that are siblings of a p element. For instance:
<p>This is a paragraph.</p>
<div>This div will be yellow.</div>
<div>This div will also be yellow.</div>
<p>Another paragraph.</p>
<div>This div won't be yellow.</div>
In this example, the first two div elements will have a yellow background because they are siblings of the first p element. The last div won’t be affected because it’s not a sibling of the preceding p.
Key points to remember
- Sibling Relationship: The elements must share the same parent.
- Order Doesn’t Matter: The sibling element can come before or after the specified element.
- Multiple Siblings: The selector can match multiple siblings of the specified element.
Use Cases
- Styling consecutive elements: For example, styling every other paragraph in a list.
- Creating layout structures: By targeting specific sibling elements, you can create complex layouts.
- Applying conditional styles: Based on the presence of a sibling element, you can apply specific styles.
By understanding the General Sibling Combinator, you can create more precise and flexible CSS styles.