I cannot find the difference between these two selectors. Both seem to do the same thing i.e select tags based on a specific attribute value containing a given string.
For [attribute~=value]
: http://www.w3schools.com/cssref/sel_attribute_value_contains.asp
For [attribute*=value]
: http://www.w3schools.com/cssref/sel_attr_contain.asp
The CSS Attribute Selector is used to select an element with some specific attribute or attribute value. It is an excellent way to style the HTML elements by grouping them based on some specific attributes and the attribute selector will select those elements with similar attributes.
Selector: tells CSS which elements to style. Property: tells CSS what you are changing. Value: tells CSS to how you want that element to change.
CSS [attribute^="value"] Selector The [attribute^="value"] selector is used to select elements with the specified attribute, whose value starts with the specified value. The following example selects all elements with a class attribute value that starts with "top": Note: The value does not have to be a whole word!
The [attribute=value] selector is used to select elements with the specified attribute and value.
w3schools is a notoriously unreliable source, and not related to the W3C. Instead, consult the official CSS standard:
[attribute~=value]
matches any entry in a space-delimited list.
It matches attribute="a value b"
, but not attribute="a valueb"
.
[attribute*=value]
matches any substring.
It matches attribute="a value b"
and attribute="a valueb"
, but not attribute="x"
.
According to Specs:
[att~=val]
: Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.
[att*=val]
: Represents an element with the att attribute whose value contains at least one instance of the substring "val". If "val" is the empty string then the selector does not represent anything.
So, the main difference is that *
means that the val
may be anywhere in the value of attribute, but in case of ~
the val
must me exact part of value which can be separated by whitespaces (like class
attribute).
You can see it in action here: http://jsfiddle.net/kizu/bPX9n/
the [class*=val] is applied to both divs, but the [class~=val] is applied to the one where the val
is separated by whitespaces from the other parts of an attribute.
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