CSS difference between attribute selectors with tilde and star?

The ~= is called Attribute Contains Word Selector.

So when you use: [attrName~=stuff] it will match every element that has attrName's value equal to "stuff" or containing "stuff ", " stuff " or " stuff". Examples:

  • Selector: [name~=ball]
  • Matches:
    • <input name="ball" type="text">
    • <input name="ball " type="text">
    • <input name=" ball" type="text">
    • <input name=" ball " type="text">
    • <input name="doesnotmatter ball asLongAsballIsBetweenWhiteSpaces" type="text">

The *= is called Attribute Contains Substring Selector.

When you use [attrName*=stuff] it will match if stuff is present in the attribute's value, even if inside some word, such as:

  • Selector: [name*=ball]
  • Matches:
    • All those that were matched by [name~=ball], but also...
    • <input name="whatball" type="text">
    • <input name="ballwhat" type="text">
    • <input name="whatballwhat" type="text">
    • and so on, as long as the attribute's value contains the string ball.

Note: the links above point to jQuery's website just because, for those specific selectors, I find their reference to be the best, but those attribute selectors are from CSS 2.1 and have been supported since IE7.

MSDN also calls the contains word selector Whitespace Attribute Selector.

Finally, click here for a demo fiddle.


The asterisk attribute selector *= matches any substring occurrence. You can think of it as a string contains call.

Input Matches *=bar
foo No
foobar Yes
foo bar Yes
foo barbaz Yes
foo bar baz Yes

The tilde attribute selector ~= matches whole words only.

Input Matches ~=bar
foo No
foobar No
foo bar Yes
foo barbaz No
foo bar baz Yes

div {
  padding: 10px;
  border: 2px solid white;
}


[attribute*=bar] {
  background: lightgray;
}

[attribute~=bar] {
  border-color: red;
}
<div>no attribute</div>
<div attribute="foo">attribute="foo"</div>
<div attribute="foobar">attribute="foobar"</div>
<div attribute="foo bar">attribute="foo bar"</div>
<div attribute="foo barbaz">attribute="foo barbaz"</div>
<div attribute="foo bar baz">attribute="foo bar baz"</div>

Tags:

Css