The General Sibling selector (~) in CSS is used to select all elements that are siblings of a specified element and follow it in the document tree. This selector is quite powerful as it allows you to apply styles to multiple elements based on the presence or structure of previous sibling elements.
Syntax
A ~ B { /* styles */ }
Here, A is the preceding element, and B is the element you want to style. The selector targets all B elements that are siblings of A and come after A.
Let's say you have an HTML structure where you want to style certain paragraphs only if they are preceded by a heading. Here's how you can use the General Sibling selector.
generalSiblingSelector.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>General Sibling Selector Example</title> <link rel="stylesheet" href="../../css/selectors/generalSiblingSelector.css"> </head> <body> <p>Demo Application</p> <h2>Section 1</h2> <p>This is the first paragraph in Section 1.</p> <p>This is the second paragraph in Section 1.</p> <h2>Section 2</h2> <p>This is the first paragraph in Section 2.</p> <p>This is the second paragraph in Section 2.</p> <div>A non-paragraph element</div> <p>This is a paragraph preceded by a heading, so appear in blue.</p> </body> </html>
generalSiblingSelector.css
h2 ~ p { color: blue; font-weight: bold; }
Open ‘generalSiblingSelector.html’
in browser, you can see below kind of screen.
The h2 ~ p selector will apply the blue color and bold font to all <p> elements that are siblings and come after any <h2> element, regardless of whether they are immediately adjacent or separated by other elements.
In this example, all paragraphs that follow any <h2> element will be styled according to the h2 ~ p selector. This includes paragraphs directly following the <h2> elements, as well as those that might have other elements (like a <div>) between them.
Previous Next Home
No comments:
Post a Comment