Thiemos Archiv
- Monday, 2020-05-11 16:41
- I might have found the very first real-world application for the
~
CSS selector in my life. Or the last time I used it was so long ago that I totally forgot it exists. What does it do?CSS provides a bunch of mostly 1-character »combinators«.
>
(greater-than sign)+
(plus sign)~
(tilde)
>
>
is called the »child combinator«. It selects only nodes that are exactly one level deeper inside another node, but not deeper. It's perfect for lists and tables where the elements have a guaranteed parent-child relationship.
In the following example,ul > li
select only<li>
elements that are direct children of the outer<ul>
, but not other<li>
elements that are part of deeper nested lists:<ul>
<li>When a list contains another list, like this:
<ol>
<li>List item on the second level
…
The
>
is part of CSS 2 and exists since 1998.+
+
is a »sibling combinator«, more specifically the »adjacent sibling combinator«. It selects only the node directly after the first, on the same level.
In the following example,h2 + p
will select only the first paragraph, but not the second:<h2>Headline</h2>The
<p>Initial paragraph
<p>More paragraphs
…
+
also exists since 1998. (Earlier drafts of CSS used~
instead of+
.)~
~
is the »general sibling combinator«. It selects all nodes that follow the first on the same level.
In the following example,.error ~ p
selects all<p>
elements after an error, but not the<p>
before.<p>Text
<div class="error">From here on, everything is wrong.</div>
<p>Text
…
The
~
was added in CSS 3 and exists since 1999.Note that the space is also considered a combinator, just like the others listed above. You will realize why if you try to remove the space. The selector's meaning is entirely different then. The space is called the »descendant combinator«. It selects nodes that are anywhere inside another node, no matter how deeply nested, but at least one level deeper.
Kommentare zu diesem Beitrag können per E-Mail an den Autor gesandt werden.
~ can be useful to bend a flat document tree into a less linear rendering, but in most cases there are already class names or ids present which are better suited for the same result.