A complete guide to CSS combinators in 2022. You can find everything you need to know about CSS Combinators in this blog.
Hey š, I am Kunaal. In the article, we'll talk about something called CSS Combinators. You may have seen something likeĀ
div ~ span
Ā orĀ div > p
Ā and that's exactly what we are going to discuss in this blog. So without ado, let's get started.They are the combination of simple CSS selectors. What do I mean? The class selector, id selector, or even tag selectors - everything in CSS is a simple selector and when we use more than 1 selector it makes a combinator selector. For instance;
div
Ā andĀ p
Ā are simple selectors but togetherĀ div p
Ā they are combinator selectors.Basically, the combinator selector defines a relationship between the selectors.
It basically selects all the elements inside or descendant to the specified element. For instance;
div p {
color : red;
}
It will colour/style all theĀ
<p>
Ā elements insideĀ <div>
Ā elements including all the nestedĀ <p>
Ā elements. Nested elements are those that are nested in a container like<div>
<p>Paragraph</p>
<h1><p>Nested Paragraph</p><h1>
</div>
Its selects all the elements inside the specified element excluding the nested elements. For instance,
div > p {
color: red;
}
So the above example will select all theĀ
<p>
Ā elements ofĀ <div>
Ā element but it will not affect the nestedĀ <p>
Ā elements.Adjacent Sibling Selector selects the elements just after element of the specified element. For instance,
div + p {
color: red;
}
So the above code will only select theĀ
<p>
Ā element which is just after theĀ <div>
Ā element. Example -This is the last one and it selects all the elements after the specified element. For instance,
div ~ p {
color: red;
}
The above example will select all theĀ
<p>
Ā elements after theĀ <div>
Ā element. Example:So that's it. This was all about CSS Combinators, I hope you liked the article and this article was helpful for you. If you liked it or don't want to miss out on more interesting web dev tips and tricks, you can follow me on myĀ InstagramĀ or you can just simple subscribe myĀ YouTubeĀ channel if you want to master web development.
Thanks for reading