Given the following CSS selectors
[attribute~=value] { } [attribute*=value] { }
Should both of the selectors above do exactly the same thing? Or is there a difference?
I believe that there is some kind of a difference, but what? The only one which I spot is that the first of each pair is in the spec of CSS 2 and the second in spec of CSS 3.
Is there anything else?
Fiddle
The [attribute*="value"] selector is used to select elements whose attribute value contains a specified value.
In CSS, the symbol tilde(~) is know as Subsequent-sibling Combinator (also known as tilde or squiggle or twiddle or general-sibling selector). As the name suggests it is made of the “tilde” (U+007E, ~) character that separates two sequences of simple selectors.
2 Answers. Show activity on this post. + will only select the first element that is immediately preceded by the former selector. ~ selector all the sibling preceded by the former selector.
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:
[name~=ball]
<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:
[name*=ball]
[name~=ball]
, but also...<input name="whatball" type="text">
<input name="ballwhat" type="text">
<input name="whatballwhat" type="text">
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With