A Complete guide on CSS combinators 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 or you may have seen somethings like div ~ span
or div > p
that exactly what we are going to discuss today. So without wasting more time let's start.
📌 What are combinators ?
Well these are the combination of simple CSS selectors. What do I mean ? Means the class selector, id selector or even tag selectors everything in CSS are simple selector and when we use more than 1 selector it make a combinator selector. For instance.
div
and p
are simple selector but together div p
they are now combinator selectors.
Basically combinator selector defines a relationship between the selectors.
1. Descendant Selector
Its 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 who are nested in a container like
<div>
<p>Paragraph</p>
<h1><p>Nested Paragraph</p><h1>
</div>
2. Child Selector ( > )
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.
3. Adjacent Sibling Selector (+)
Adjacent Sibling Selector selects the elements the 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 -
4. General Sibling Selector (~)
This is the last one and it selects all the elements after the specified element. For instance,
div ~ p {
color: red;
}
Above example will select all the <p>
elements after the <div>
element. Example -
📌 Wrap up
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 do liked it or don't want to miss out 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
Top comments (4)
Something really amazing. Learning never stop. Everyday you learn something new. IT's very informative tutorial.
Thank you, this has been very useful. Does anybody know good examples, when some of the combinators can be a good choice?
They could be useful instead of using ID and classes
Learned something new, thanks!