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>
This HTML will end up on the browser like this:
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;
}
This rule will affect the appropriate elements that were specified in the written rule and end up looking like this:
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!
Top comments (1)
Hey hey! Cool post, but just wanted to recommend that you might want to tag it with a few tags to make it easier for folks to discover. 🙂