Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

Searching for the ~ character isn't easy. I was looking over some CSS and found this

.check:checked ~ .content { } 

What does it mean?

like image 510
Tarang Avatar asked May 28 '12 09:05

Tarang


People also ask

What does the tilde mean in CSS?

In CSS, the tilde symbol is known as subsequent-sibling combinator, which separates two compound selectors. The elements that are represented by the two compound selectors have the same parent element. The first selector precedes (but not necessarily immediately) the element that is represented by the second selector.

What are CSS selectors?

A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.

What symbol do we use to for the adjacent sibling selector?

Adjacent Sibling Selector (+) The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".

How do I target a previous sibling in CSS?

No, there is no "previous sibling" selector. On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2.


1 Answers

The ~ selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

Consider the following example:

.a ~ .b {    background-color: powderblue;  }
<ul>    <li class="b">1st</li>    <li class="a">2nd</li>    <li>3rd</li>    <li class="b">4th</li>    <li class="b">5th</li>  </ul>

.a ~ .b matches the 4th and 5th list item because they:

  • Are .b elements
  • Are siblings of .a
  • Appear after .a in HTML source order.

Likewise, .check:checked ~ .content matches all .content elements that are siblings of .check:checked and appear after it.

like image 179
Salman A Avatar answered Oct 12 '22 20:10

Salman A