Open In App
Related Articles

CSS element1~element2 Selector

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 elements have a common parent element. 

Syntax:

element1~element2 {
      /* CSS Property */
}

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

html

<!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 the same parent element. So CSS property will not apply. 

html

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


Last Updated : 06 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads