Skip to content
Related Articles

Related Articles

CSS | element1~element2 Selector
  • Difficulty Level : Basic
  • Last Updated : 08 Jan, 2019

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).




<!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>                    

Output:

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






<!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>                    

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :