February 27, 2012

What is ~ for CSS

Question by Lap Ming Lee

I want to know what the ~ is used for in CSS.

e.g.

#confirmPage:target ~ #navigation #confirm-link,

Answer by minitech

It means “general sibling”. The selector:

a ~ b

matches every element matching b that comes after an element matching a, within the same parent element. For example, take this structure:

<p>
    <span>Span 1</span>
    <strong>Strong emphasis</strong>
    <span>Span 2</span>
</p>

The selector p span ~ span will match the second <span>.

Answer by Starx

The tilde(~) is used for the indirect adjacent combinator as part of a selector. Its part of CSS Sibling Combinator. [docs here]

If you see adjacent selector a + b the style will match once the b comes right after a

But, a ~ b generalizes the selection so that b can come to any position after a.

Example:

h1 ~ pre

represents a pre element following an h1. It is a correct and valid, but partial, description of:

<h1>Definition of the function a</h1>
<p>Function a(x) has to be applied to all figures in the table.</p>
<pre>function a(x) = 12x/13.5</pre>
...

Please fill the form - I will response as fast as I can!