CSS Combinators: General Sibling Selector

jdc1492

Jonathan Cohen

Posted on June 29, 2021

CSS Combinators: General Sibling Selector

We've come to the end of the CSS combinator series. The final selector that will be discussed is the general sibling combinator.While it isn't as specific as we often aim when writing CSS rules, the selector still has it uses. The selector is used when a '~' symbol is placed between two elements. This tells our CSS to look for the second element that is a sibling of the first. No other requirement is necessary. Lets look at an example:

<div>
    <h1>The Messenger</h1>
    <p>Definitely on of my favorite indie games.</p>
    <div>Something within the div that isn't a p 
    element</div>
    <p>While I've played and finished the FFVII Remake, I haven't played the original.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

This HTML will end up on the browser like this:
Screen Shot 2021-06-29 at 5.19.19 PM

Lets create a CSS rule using the general sibling selector. In this case the goal is to affect the two p elements that are siblings of an H1 tag.

h1 ~ p {
    font-weight: bold;
    background-color: #471;
    color: #fff;
    padding: .5em;
}
Enter fullscreen mode Exit fullscreen mode

This rule will affect the appropriate elements that were specified in the written rule and end up looking like this:

Screen Shot 2021-06-29 at 5.17.54 PM

The two p elements are affected, as they should be, leaving the other sibling elements alone without any changes to the look of them. CSS sibling combinator can help so much. I'm still getting used to using them all, when it seems necessary. As always, take time to practice using these 4 selectors and see what else you may come across. Happy Coding!

💖 💪 🙅 🚩
jdc1492
Jonathan Cohen

Posted on June 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related