CSS difference between attribute tilde and star selectors?

Given the following CSS selectors

[attribute~=value] { } [attribute*=value] { } 

If both of the above selectors do the same thing? Or is there a difference?

I think there is some difference, but what? The only thing I see is that the first of each pair is in the CSS 2 specification, and the second is in the CSS 3 specification.
Is there anything else?

Fiddle

+7
css
source share
2 answers

The first is used to select elements containing a whole specific word. The latter is used to select any string constraint; it does not have to be a whole word.

 div { padding: 30px; } /* Matches "foo", but not "fo" */ [attribute~=foo] { background: lightcoral; } /* Matches both "bar" and "ba" */ [attribute*=ba] { background: lavender; } 
 <div attribute="foo"></div> <div attribute="bar"></div> 
+4
source share

~= called Attribute contains Word Selector .

Therefore, when you use: [attrName~=stuff] , it will correspond to each element with attrName 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">

*= called Attribute contains Substring Selector .

When you use [attrName*=stuff] , it will match if there is stuff in the attribute value, even if inside a word, for example:

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

Note: the links above point to the jQuery site only because for these specific selectors I consider their links to be the best, but these attribute selectors are from CSS 2.1 and are supported with IE7 .

MSDN also calls the word selector Whitespace attribute selector .

Finally, click here for a demo fiddle .

+3
source share

All Articles