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

标签 css css-selectors

此选择器用于选择属性值包含给定单词的元素。

例如 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>

关于CSS [attribute~=value] 选择器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27838509/

相关文章:

html - 使用 CSS 或 XPath 选择器解析 HTML?

javascript - 具有 javascript 值的组合框在 iPad 上不起作用

css - 用于 Xenforo 集成的导航栏 CSS Bootstrap

html - Flex CSS - 列表项的左边距不仅仅是最后一个 child

html - 转换 CSS 属性不适用于 <a> 元素

javascript - id vs 类选择基准

jquery - CSS - 添加类到 3n+4 'visible' 列表项

CSS nth-child 不起作用

javascript - 带 Ui-bootstrap 的周选择器

html - 如何使父属性不覆盖后代