As part of the comiCSS webcomic, I drew a short cartoon to explain how the combinators (and the universal selector) work. Hopefully, it helps illustrate how the CSS combinators work and what elements would be impacted by them:
It doesn't include the descendant combinator because it would be just a blank space and it would be weird to do that in comic form. Just an empty space in the middle of the panel.
A CSS combinator is a tool that combines selectors, providing additional meaning and expressing relationship between them.
There are five CSS combinators:
Descendant combinator (
): indicates that the second element is a descendant (at any level) of the first one. Example:
a bwill select all the
<b>that are inside of an
Child combinator (
>): specifies that the second element is a direct descendant (first level only) of the first one. Example:
a > bwill select all the
<b>that are direct children of an
Adjacent sibling combinator (
+): indicates that the second element follows the first one directly in the code (first sibling). Example:
a + bwill select all the
<b>that directly follow an
General sibling combinator (
~): states that the second element follows the first one in the code (any sibling as long as it's after the first element). Example:
a ~ bwill select all the
<b>that follow (siblings) an
Column combinator (
||): indicates that the second element is in the same column as the first element.
The column combinator is considered experimental. No browser supports it now, and it is at risk of being removed from the standard. So probably not a good idea to use it in production.
If you noticed, the reply to the column combinator is in blue instead of yellow: the ones answering are the other combinators as they are in the same column!
Combinators and Specificity
This may sound a bit counterintuitive, but CSS combinators do not add to the specificity of a selector. This means that things like a b and a > b have the same specificity (even when one is more specific logically than the other.)
This is the way it is and it will likely never change, as they explain on this thread of the W3C working group mailing list. Giving a specificity value to the combinators would:
- add complexity to the specificity calculations;
- impact the styling of existing sites.
The first point is arguable. The second one present a bigger challenge: if the specificity was not changed because it would impact many existing websites almost 20 years ago, imagine how many more it could impact now.