CSS | element~element Selector

The element ~ element selector in CSS is used to match the second element if it follows the first element (it doesn’t need to be immediate). They both should have same parent element.

Syntax:

element ~ element {
    //CSS Property
}

Example 1: In the below program you can see that “p ~ ul” will select and style only the second unordered list which comes after paragraph and not the first list which is alone.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>
            CSS element ~ element Selector
        </title>
        <style>
            p ~ ul {
                color:white;
                background: green;
            }
        </style>
    </head>
    <body style = "">
        <h2 style = "color:green; text-align: center;">
            CSS element ~ element Selector
  
        </h2>
          
        <div>Searching algorithms</div>
        <ul>
          <li>Binary search</li>
          <li>Linear search</li>
        </ul>
          
        <p>Sorting Algorithms</p>
        <ul>
          <li>Merge sort</li>
          <li>Quick sort</li>
        </ul>
    </body>
</html>

chevron_right


Output:
el-el

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>
            CSS element ~ element Selector
        </title>
        <style>
            p ~ span {
                color:white;
                background: green;
            }
        </style>
    </head>
    <body style = "">
        <!--<h1 style = "color:green;text-align: center;">-->
        <!--    GeeksforGeeks-->
        <!--</h1>-->
        <h2 style = "color:green; text-align: center;">
            CSS element ~ element Selector
  
        </h2>
        <span>This is the first span.</span>
        <p>This is the first paragraph.</p>
        <code>Some code</code>
        <span>A computer science  </span>
        <code>More code.....</code>
        <span> portal for geeks.</span>
    </body>
</html>

chevron_right


Output:
el-el2

Supported Browsers: The browser supported by element ~ element selector are listed below:

  • Apple Safari 3.2
  • Google Chrome 4.0
  • Firefox 3.5
  • Opera 9.6
  • Internet Explorer 7.0


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.