CSS Subsequent-sibling Combinator

The CSS subsequent-sibling combinator (~) is used to style all elements that are siblings and come after a specified element, regardless of whether they are immediate siblings or not. This combinator is more general than the next-sibling combinator (+).

The syntax for the subsequent-sibling combinator is:

</>
Copy
selector1 ~ selector2 {
    property: value;
}

Where:

ParameterDescription
selector1The reference element.
selector2All subsequent sibling elements that match this selector.
propertyA CSS property (e.g., color, margin, etc.).
valueThe value assigned to the CSS property.

Examples

Styling All Paragraphs After a Heading using Subsequent-sibling Combinator

In this example, we style all <p> elements that come after an <h1> element, setting their text color to blue.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        h1 ~ p {
            color: blue;
        }
    </style>
</head>
<body>
    <h1>Heading 1</h1>
    <p>This paragraph is styled.</p>
    <p>This paragraph is also styled.</p>
    <div>This div is not styled.</div>
</body>
</html>

Styling All List Items After a Specific Item using Subsequent-sibling Combinator

Here, we style all <li> elements that come after a specific <li> with the class highlight, setting their font weight to bold.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        li.highlight ~ li {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <ul>
        <li class="highlight">Highlighted Item</li>
        <li>This item is styled.</li>
        <li>This item is also styled.</li>
    </ul>
</body>
</html>

Styling All Inputs After a Label using Subsequent-sibling Combinator

In this example, we style all <input> elements that come after a <label>, adding a border color of green.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        label ~ input {
            border: 2px solid green;
        }
    </style>
</head>
<body>
    <label>Name:</label>
    <input type="text" name="name">
    <br>
    <input type="text" name="unrelated">
</body>
</html>