What is the general sibling combinator in CSS?

The general sibling combinator in CSS is represented by the tilde symbol ~ and is used to select elements that share the same parent and come after the first element. The general sibling combinator selects all siblings, not just the immediately following sibling.

Here is the syntax:

selector1 ~ selector2 {
  /* styles */
}

In this syntax, selector1 is the reference element, and selector2 is the target element that you want to style. The styles will apply to all elements that match selector2 and are following siblings of an element that matches selector1.

For example, consider the following HTML:

<div>
  <h2>Title</h2>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
</div>

If you wanted to change the color of all <p> elements that come after an <h2> element within the same parent <div>, you would use the general sibling combinator like this:

h2 ~ p {
  color: blue;
}

This CSS rule will select all <p> elements that are siblings of the <h2> and come after it, resulting in "Paragraph 1", "Paragraph 2", and "Paragraph 3" all being colored blue.

It's important to note that the general sibling combinator does not select elements that come before the first element, nor does it select the first element itself. It only targets subsequent siblings that match the second selector and share the same parent.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon