When learning CSS, the selectors that you will come across are the commonly used ones such as class selector (.), id selector (#), universal selector (*) and of course, type and attribute selectors.
When I started learning CSS, understanding these selectors was exciting. I thought to myself, I’m finally a CSS ninja 🙌. Well, now you know how I felt the day I realized that there are more where these came from ☹️.
Today, we will be focusing on the combinator selectors:
~ Don’t worry, these selectors are just as easy to understand and use as the commonly used ones listed above.
I know what you’re thinking, why are they called combinator selectors? Well, these group of selectors are called combinator selectors because they combine two elements together. i.e They are used in between two HTML elements. For example,
p + p You can’t do something like this:
p + It won’t work.
Enough of the talk. It’s time we get started.
Child Selector (>)
> selects direct children of a particular element. Take a look at the HTML and CSS below.
>selects the immediate child of the outer-container div, only the first and third paragraphs will have a color of red (See result above). The second paragraph will still have its default color since it is not an immediate descendant of the outer-container div.
General Sibling Selector (~)
This selector looks for all siblings that share the same parent with it. Take a look at the HTML and CSS below.
The above CSS will cause the text in the second and fourth paragraphs to turn red. (See result above)
What just happened?
~ selects all
pelements that are siblings to itself. Since the second and fourth paragraphs are its sibling, they are selected. You will notice that the third paragraph wasn’t selected. Well, the third paragraph is nested inside another div which means they do not share the same parent. It is not a sibling of the first paragraph.
Adjacent Sibling Selector (+)
The adjacent sibling selector uses the plus (+) symbol. It targets element(s) that is a direct sibling to itself and shares the same parent with itself.
It is similar to the general sibling selector but the difference is that the second/sibling element has to directly follow the first element.
Take a look at the HTML and CSS snippet below.
The CSS above will target only the second paragraph. This is because the second paragraph is a direct sibling of the first paragraph and they share the same parent. The Fourth paragraph wasn’t selected because it’s not adjacent to the first paragraph. If we remove the div block and h1 elements and apply the same CSS above, then the second and fourth paragraphs will be selected.
Whew. That brings us to the end of this article. I hope you enjoyed it and learned something from it.
Please don’t forget to give this article a clap 🤪. Thank you.