If we rank the popularity of the CSS combinators, tilde is probably at the bottom of the list. It is a nifty little combinator written for niche situations!
Let's take a step back and get to know the CSS combinators :
Ranking CSS Combinators :
1." "
: Descendant combinator
The most popular CSS combinator is the descendant combinator.
Confused what " "
does ? Here's the syntax :
.card-container button-container{
/* some property here */
}
As a Front-end Developer , you end up using this operator without realizing that you are using it ! What it does, is selects the second element only if the first element is one of its ancestors.
You can play around with the code here for better understanding : code sample
2.>
: Child combinator
In a close second is the child combinator , and it's job is to select the second element only if it is the direct child element of the first element.
Examples will clear your confusion :
card-container > p{
/* some property here */
}
Here's a code sample similar to the code sample above : code sample
3.+
: Adjacent sibling combinator
In my coding journey I haven't had the chance to use the last two on our ranking list in my projects yet , but here goes !
The plus , or the adjacent sibling combinator , is used to select the adjacent element of first element , if it matches with the second element.
Example :
h1 + p{
/* some property here */
}
Here's a code snippet to help you understand better : code sample
4.~
: General sibling combinator
Last but certainly not the least , is tilde. Known technically as the general sibling combinator . Or worm . Or squiggly line. Whatever you wanna call it , it's job is to select any siblings of the first element , which match the second element.
Here's how :
card-container-first-batch ~ rest
It is a very very corner case, but it exists. And hence our job to know!
Here's a code sample similar to the code sample above : code sample
So summarizing :
There are 4 types of CSS combinators: descendant (" ") , child(>) , adjacent sibling(+) , and general sibling(~).
Use them carefully , and hope your code never breaks !
For more such fun bits ( if you think css is fun 😂 )
Follow me on twitter , and check out my github , see you next time !
Top comments (4)
point 3 and point 4 code examples links does not have the examples of + and ~
Good walkthrough.
plus (+) is my favorite selector, great idea to rank these selectors
Thank you Darshan!