Open In App

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




<!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: Example 2: 






<!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: Supported Browsers: The browser supported by element ~ element selector are listed below:


Article Tags :