CSS general sibling combinator
Created By: chatGPT
CSS General Sibling Combinator (
~
) allows you to select elements that are siblings and appear after a specified element. Unlike the adjacent sibling combinator (+
), which only selects the immediate next sibling, the general sibling combinator can select any number of siblings that follow the specified element./* Select all <p> elements that follow a <div> */
div ~ p {
color: blue;
font-style: italic;
}
In this example, any
<p>
element that comes after a <div>
sibling in the HTML structure will have blue color and an italic font style. This is particularly useful for styling elements based on their relationship without modifying the HTML structure.<div>Sample Div</div>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Third Paragraph</p>
Here's another example where we can style specific sections depending on their sibling status. If you want to change the background of all
<h2>
elements that come after an <article>
element, you can use the following CSS:article ~ h2 {
background-color: yellow;
}
In this case, every
<h2>
that follows an <article>
in the document will receive a yellow background, allowing you to visually distinguish these headings based on their placement in the DOM.<article>Sample Article</article>
<h2>First Heading</h2>
<h2>Second Heading</h2>