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
  &lt;/p&gt;&lt;div&gt;&lt;p&gt;
        This paragraph is inside a div 
        and will not be blue.
     &lt;/p&gt;&lt;/div&gt;&lt;p&gt;
     This paragraph 1 after the div 
     and will be blue.
  &lt;/p&gt;&lt;p&gt;This paragraph 2 after the 
     div and will be blue.
  &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

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;
    }
&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="container"&gt;&lt;h3&gt;This is an h3 tag&lt;/h3&gt;&lt;p&gt; 
        This is a p tag that immediately follows the h3 tag.
    &lt;/p&gt;&lt;p&gt;
        This is another p tag, but it is not immediately 
        after the h3 tag.
    &lt;/p&gt;&lt;/div&gt;&lt;p&gt;This is a p tag which is outside the parent div element.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *