0
0
CssHow-ToBeginner · 3 min read

How to Use General Sibling Selector in CSS: Simple Guide

The CSS general sibling selector (~) selects all sibling elements that share the same parent and come after a specified element. Use it like element1 ~ element2 to style all element2 siblings following element1.
📐

Syntax

The general sibling selector uses the tilde symbol ~ between two selectors. It selects all siblings of the first element that match the second selector and come after it in the HTML.

  • element1: The reference element.
  • ~: The general sibling combinator.
  • element2: The siblings to select that come after element1.
css
element1 ~ element2 {
  /* CSS rules here */
}
💻

Example

This example shows how to color all paragraphs that come after a heading inside the same container.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>General Sibling Selector Example</title>
<style>
h2 ~ p {
  color: teal;
  font-weight: bold;
}
</style>
</head>
<body>
<section>
  <h2>Title</h2>
  <p>This paragraph is styled because it follows the h2.</p>
  <p>This paragraph is also styled.</p>
  <div>Not a paragraph, so not styled.</div>
  <p>This paragraph is styled too.</p>
</section>
<section>
  <p>This paragraph is not styled because it does not follow an h2 sibling.</p>
</section>
</body>
</html>
Output
A page with a section titled 'Title' in normal black text, followed by three paragraphs in teal and bold font. Another section below has a black paragraph not styled.
⚠️

Common Pitfalls

One common mistake is confusing the general sibling selector ~ with the adjacent sibling selector +. The adjacent selector only targets the very next sibling, while the general sibling targets all siblings after the first element.

Also, the selector only works on siblings sharing the same parent element. It does not select nested or unrelated elements.

css
/* Wrong: only selects the next sibling */
h2 + p {
  color: red;
}

/* Correct: selects all following siblings */
h2 ~ p {
  color: teal;
}
📊

Quick Reference

Remember these tips when using the general sibling selector:

  • Use ~ between two selectors to select all siblings after the first.
  • Only siblings with the same parent are selected.
  • It selects all matching siblings after the first, not just the immediate next.
  • Useful for styling multiple elements based on a previous element.

Key Takeaways

The general sibling selector (~) selects all siblings after a specified element sharing the same parent.
It differs from the adjacent sibling selector (+) which selects only the next sibling.
Only elements with the same parent are affected by this selector.
Use it to style multiple elements that come after a reference element in the HTML.
Remember it does not select nested or unrelated elements.