CSS - General Sibling Selectors



General Sibling Selectors in CSS

CSS general sibling selector ( "~" ) selects all the elements that are siblings of a specified element sharing the same parent. It will select all matching siblings, not just the one immediately following. A tilde ( "~" ) symbol is used to denote the general sibling.

Syntax

The syntax for CSS general sibling selectors is as follows:

selector1 ~ selector2 {
    /* property: value; */
    color: #04af2f
}

Example of General Sibling Selectors

In this example, we have used general sibling selector to change the text color of all p elements that are immediate siblings of the div element.

<!DOCTYPE html>
<html lang="en">
<head>
   <style>
      div{
         border: 2px solid #031926;
      }
      div ~ p {
         color: #04af2f;
      }
   </style>
</head>

<body>
      <p>
         This paragraph is above the div 
         and will not be blue
      </p>
      <div>
         <p>
            This paragraph is inside a div 
            and will not be blue.
         </p>
      </div>
      <p>
         This paragraph 1 after the div 
         and will be blue.
      </p>
      <p>This paragraph 2 after the 
         div and will be blue.
      </p>
</body>
</html>

Example 2

In this example, we have used a general sibling selector to change the background color and font of all the p elements after the h3 tag.

<!DOCTYPE html>
<html>
<head>
    <style>
        .container {
            padding: 20px;
            border: 2px solid #031926;
            font-family: Verdana, sans-serif;
        }
        h3 ~ p {
            font-family: Verdana, sans-serif;
            font-size: 20px;
            font-style: italic;
            background-color: #04af2f;
            color: white;
        }
    </style>
</head>

<body>
    <div class="container">
        <h3>This is an h3 tag</h3>
        <p> 
            This is a p tag that immediately follows the h3 tag.
        </p>
        <p>
            This is another p tag, but it is not immediately 
            after the h3 tag.
        </p>
    </div>
    <p>This is a p tag which is outside the parent div element.</p>
</body>

</html>
Advertisements