CSS [attribute~=value] 选择器行为

CSS [attribute~=value] selector behaviour

此 selector 用于 select 具有包含给定词的属性值的元素。

例如 title~="image" 将匹配 title="image"title="first image"

但它不会匹配 title="images",即使 "images" 包含 "image"。

谁能解释一下为什么?谢谢。

来自CSS Selectors specification

[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.

如果要匹配title="images",可以使用[att*=val] substring-matching selector代替:

[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.

[class*="foo"] {
  margin: 0;
  color: green;
}
<figure class="foo">foo</figure>
<figure class="foo bar">foo bar</figure>
<figure class="bar foo">bar foo</figure>
<figure class="foos bar">foos bar</figure>