Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Selects every element that are preceded by a element with CSS
The CSS general sibling selector (~) selects elements that are siblings and come after a specified element. The syntax element1 ~ element2 targets all element2 elements that are preceded by element1 at the same level in the HTML structure.
Syntax
element1 ~ element2 {
/* CSS properties */
}
Example: Selecting Lists After Paragraphs
The following example selects all <ul> elements that are preceded by a <p> element −
<!DOCTYPE html>
<html>
<head>
<style>
p ~ ul {
color: white;
background-color: blue;
padding: 10px;
margin: 10px 0;
}
p {
font-weight: bold;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>Demo Website</h1>
<h2>Health Benefits</h2>
<div>
<p>Vegetables are good for health.</p>
<ul>
<li>Spinach</li>
<li>Onion</li>
<li>Capsicum</li>
</ul>
</div>
<p>Fruits are good for health.</p>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Kiwi</li>
</ul>
<ul>
<li>This list is not styled (no preceding paragraph)</li>
</ul>
</body>
</html>
The page displays headings and content. The two unordered lists that come after paragraph elements have white text on blue backgrounds with padding, while the last list (without a preceding paragraph) remains unstyled.
Key Points
- The general sibling selector (~) only affects elements that come after the specified element
- Both elements must be siblings (at the same level in the DOM)
- Unlike the adjacent sibling selector (+), the general sibling selector matches all qualifying siblings, not just the immediately following one
Conclusion
The general sibling selector (~) is useful for styling elements based on the presence of preceding siblings. It provides flexibility in targeting multiple elements that share a common sibling relationship.
Advertisements
