maettig.com

Thiemos Archiv

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«.

>

> is called the »child combinator«. It selects only nodes that are exactly 1 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>
<p>Initial paragraph
<p>More paragraphs

The + 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 selectors 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 1 level deeper.

mehr schreiben


(Links wie gewohnt formatieren.)

[ ← Zurück zur Übersicht ]

Impressum & Datenschutz