Open In App
Related Articles

CSS element~element Selector

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

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 the 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 the paragraph and not the first list which is alone. 

html

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

                    

Output: el-elExample 2: 

HTML

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

                    

Output: el-el2Supported 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


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