At W3Schools they declare both | and ^ to mean: Select an element with an attribute starting with a specified value.
So what\'s the differe
As w3schools declare both | and ^ select attribute starting with a defined value
No, the |
is not used to select elements whose attribute value start with a certain value.
Here is what the W3C Spec says about these selectors. (emphasis is mine)
[att|=val]
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D).
[att^=val]
Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.
So, the |
symbol in the attribute selector would select only elements whose attribute value is either exactly the given value or starts with the given value followed by a hyphen.
As you can see in the below snippet, the attribute selector which uses |
([data-test |= 'val']
) doesn't select the element when the attribute value is like valid
whereas the attribute selector with ^
([data-test ^= 'val']
) does.
div[data-test |= 'val'] {
color: beige;
}
div[data-test ^= 'val'] {
background: red;
}
Hello
Hello
Hello
In a more real-world scenario, the attribute selector with pipe (|
) can be used to select elements and apply specific styling depending on their language (which can be set using the lang
attribute). As we can see in the snippet, |= 'en'
selects all elements whose lang
attribute is either en
or en-GB
or en-US
(or any other en-*
for that matter).
As the spec states, the primary intention of this selector was to allow language subcode matches but as BoltClock points out, this has by and large been superseded by the :lang pseudo-class selector.
div[lang |= 'en']{
font-size: 16px;
background: steelblue;
}
div[lang |= 'zh']{
font-size: 14px;
background: mediumslateblue;
}
div{padding: 4px;}
English: The grass is green in colour.
English (UK): The grass is green in colour.
English (US): The grass is green in color.
Chinese (Simplified): 草是绿色的。
Chinese (Traditional): 草是綠色的。
(Translations were by Google. Any mistake was unintentional)
Additional Information: The attribute selector which uses pipe (|
) was introduced in CSS2 and the attribute selector which uses the cap/caret (^
) was introduced in CSS3.