56

I want to know what does (~) mean in css.

#img1:hover ~ #img2 {
    opacity: 0;
}

In visual studio, i get 'unexpected character sequence' error when i use this symbol. what is the actual meaning of this in CSS. what does it do?

Monie corleone
  • 1,618
  • 1
  • 16
  • 37

2 Answers2

62

http://www.w3.org/TR/selectors/

8.3.2. General sibling combinator

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.

example

h1 ~ pre

matches that <pre> here:

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

There is also + selector, for adjacent sibling combinator: with h1 + pre the <pre> tag would have to be right after <h1>

user2513149
  • 850
  • 12
  • 15
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
29

It applies the style to all elements matching the second selector if they appear after the elements matching the first selector. For example, given an HTML snippet and CSS rule:

hr ~ p {
    font-weight: bold;
}
<p>Line one</p>
<hr />
<p>Line two</p>
<p>Line three</p>

only <p>Line two</p> and <p>Line three</p> will appear bold. In your example, I think Visual Studio is having a problem interpreting the :hover modifier, since it isn't really an element. If you remove it from the rule, it may work correctly.

Vanilla
  • 51
  • 1
  • 3
  • 9
Neil T.
  • 3,308
  • 1
  • 25
  • 30
  • Have you noticed any issues using ~ in various browsers? Latest Chrome seems to ignore it for me. – Nathan Dec 10 '18 at 21:18
  • I built a very simple [index.html] containing only the above example. It displayed correctly, so I opened the About page to get the version number to report back to you. I was on Chrome 70, but navigating to the page started the update process. When it finished, I relaunched and tried it again. So, I can say it works in Chrome 70 and 71. You might want to make sure nothing is overriding your styles. – Neil T. Dec 10 '18 at 21:29