CSS Combinators : Mastering the Use of Multiple CSS Selectors

Written by techyprogrammers | Published 2022/03/10
Tech Story Tags: css | html-css | web-development | web-dev | html5 | css3 | css-flexbox-grid-layout-guide | learn-flexbox-css

TLDRvia the TL;DR App

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.

📌 What are Combinators ?

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.

1. Descendant Selector

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>

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 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;
}
The 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 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

Written by techyprogrammers | Modern web makes tutorial on web development to master your skills.
Published by HackerNoon on 2022/03/10