Sometimes a selector may not be a simple element but a group of multiple selectors being styled in a similar fashion. These multiple simple selectors may have some dependency/relationship with one another. To define such relationships. CSS uses what is called a Combinator. So, if a selector contains more than one simple selectors, we can use combinators between two simple selectors to explain their relationship.
Heres’s the list of combinators used in CSS:
- descendant selector: Marked by ‘space’
- child selector: Marked by the greater than (>) sign
- adjacent sibling selector: Marked by the plus (+) sign
- general sibling selector: Marked by the till (~) sign
This is the relationship where one element is descendent of the other. So for instance, if you put ‘div’ and ‘p’ in a selector separated by spaces then the subsequent style will be applied to all the
tags that will fall inside the <div> element.
The difference between descendant and child is that child selector only defines the immediate child. Therefore, if the ‘div’ and ‘p’ are separated by > sign, the style will be applicable only if the p is the immediate child of div.
Adjacent Sibling Selector
So, adjacent means on the same level in the hierarchy. So if both div and p are on same level i.e. are children of same parent or don’t have a parent at all, the div + p selector will style the p element. The keyword here is adjacent. So, the p should be immediately following the div element.
General Sibling Selector
This is different from the adjacent sibling selector in the sense that no matter the adjacency, if two elements are siblings, the style can be applied to that selector. So, div and p may be sibling but p may not be immediately following div and will still be styled for div~p selector.