CSS | element1~element2 Selector

The element1~element2 selector in CSS is used to match the occurrences of element2 followed by element1. It is not important to element1 immediately followed by element2. This property works if both the elements have common parent element.

Syntax:

element1 ~ element2 {
    // CSS Property
}

Example 1: In this example, both elements have same parent element (body).



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>
            CSS element1~element2 Selector
        </title>
          
        <style>
            p ~ ul {
                background: green;
                color:white;
            }
        </style>
    </head>
      
    <body>
        <div>
            <p>Programming Languages list:</p>
            <ul>
                <li>C</li>
                <li>C++</li>
                <li>Java</li>
                <li>Python</li>
            </ul>
      
            <div>Computer Science Subjects:</div>
            <ul>
                <li>Data Structure</li>
                <li>Algorithm</li>
                <li>Operating System</li>
                <li>Computer Networks</li>
            </ul>
        </div>
    </body>
</html>                    

chevron_right


Output:

Example 2: In this example, both elements do not have have same parent element. So CSS property will not apply.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>
            CSS element1~element2 Selector
        </title>
          
        <style>
            p ~ ul {
                background: lightgrey;
                border: 2px solid green;
            }
        </style>
    </head>
      
    <body>
        <p>Programming Languages list:</p>
        <div>
            <ul>
                <li>C</li>
                <li>C++</li>
                <li>Java</li>
                <li>Python</li>
            </ul>
          
            <div>Computer Science Subjects:</div>
            <ul>
                <li>Data Structure</li>
                <li>Algorithm</li>
                <li>Operating System</li>
                <li>Computer Networks</li>
            </ul>
        </div>
    </body>
</html>                    

chevron_right


Output:

Supported Browsers: The browser supported by element1~element2 Selector are listed below:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.