CSS for Web Development

0% completed

Previous
Next
Subsequent-sibling combinator (~)

The subsequent-sibling combinator (~) selects all elements that follow a specified element, sharing the same parent—even if they are not directly adjacent. This is different from the next sibling combinator (+), which only targets the immediate next element.

Syntax

selector1 ~ selector2 { property: value; }

Explanation:

  • selector1 ~ selector2:
    • Styles all sibling elements (matching selector2) that appear after selector1 in the document, regardless of their distance.
    • Unlike the next sibling combinator, this works even if there are other elements between selector1 and selector2.

Example 1: Styling All Paragraphs After a Heading

In this example, every <p> element that follows an <h2> element within the same container is styled with a different text color. This demonstrates how the subsequent-sibling combinator targets all matching siblings, not just the first one.

HTML

. . . .

Explanation:

  • Targeting Siblings:
    • The rule h2 ~ p selects every <p> element that is a sibling of the <h2> and comes after it in the document.
  • Outcome:
    • All <p> elements directly following the <h2> (and sharing the same parent) are styled with red text, while the paragraph inside the <div> remains unaffected.

Example 2: Highlighting List Items Following a Special Item

In this example, we style all list items (<li>) that come after a list item with a specific class .highlight inside an unordered list. This technique is useful when you want to emphasize a group of items that come after a particular element.

HTML

. . . .

Explanation:

  • Special Item:
    • The list item with the class .highlight is styled distinctly.
  • Subsequent Siblings:
    • The rule .highlight ~ li applies to all <li> elements that follow the highlighted item, regardless of whether they are immediately next to it.
  • Outcome:
    • All list items following the highlighted item get a light blue background and bold text, providing a visual cue about their placement relative to the special item.

The subsequent-sibling combinator (~) is a powerful CSS selector that lets you style all elements following a specific element within the same parent. It provides flexibility beyond the immediate sibling combinator, allowing for broader, context-based styling in your layouts.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next