~

In CSS, the tilde (~) symbol is used in a specific selector known as the general sibling selector. This selector matches elements that are siblings of a specified element.

Syntax

selector1 ~ selector2

Explanation

  • selector1: This is the preceding sibling element.
  • selector2: This is the element that will be selected if it’s a sibling of selector1.

Example

p ~ div {
  background-color: yellow;
}

This CSS rule will apply a yellow background color to any div element that immediately follows a p element, sharing the same parent.

Key Points

  • The tilde selector only matches elements that are direct siblings, not nested siblings.
  • It’s often used for styling specific elements based on their position relative to other elements.
  • It can be combined with other CSS selectors to create more complex styles.

Example Usage

<p>This is a paragraph.</p>
<div>This div will be yellow.</div>
<span>This span won't be affected.</span>
<div>This div will also be yellow.</div>

In this HTML, the first and second div elements will have a yellow background because they immediately follow the p element. The span element won’t be affected.