<分区>
我正在学习 edX 中的一门 CSS 类(class),其中包括:
[class*='example'] { background-color: orange; }
在 CSS 样式表中。不熟悉那种类型的属性,所以我查了一下。本质上,它只是为使用特定类 [(或 id),取决于特定属性] 的任何东西添加样式。为什么不直接添加:
background-color: orange;
到适当的类或 id,并完成它?我缺少的这种类型的属性是否有重要用途?
标签 html css css-selectors
<分区>
我正在学习 edX 中的一门 CSS 类(class),其中包括:
[class*='example'] { background-color: orange; }
在 CSS 样式表中。不熟悉那种类型的属性,所以我查了一下。本质上,它只是为使用特定类 [(或 id),取决于特定属性] 的任何东西添加样式。为什么不直接添加:
background-color: orange;
到适当的类或 id,并完成它?我缺少的这种类型的属性是否有重要用途?
最佳答案
*
在 [class*='example']
是一个选择器,用于检索包含 example
的所有元素在类名中,而不仅仅是具有类名 example
的元素.
所以 [class*='example']
将针对以下所有内容:
<div class="iamanexample"></div>
<div class="example"></div>
<div class="whereisyourexample"></div>
鉴于 .example
或 [class='example']
只会针对第二个元素 <div class="example"></div>
以上三者。
CSS 中的其他属性选择器包括:
~
选择器: 此选择器检索其目标属性值包含确切查询值的所有元素。此选择器可以包含多个值,其形式为以空格分隔的单词列表。
|
选择器:此选择器检索其目标属性值恰好为查询值或以查询值开头且紧跟连字符的所有元素。
^
选择器:此选择器检索目标属性值以查询值开头的所有元素。
$
选择器:此选择器检索目标属性值以查询值结尾的所有元素。
检查并运行以下代码片段以获得实际示例,并在代码注释中解释上述每个选择器的工作原理:
/* all elements whose abc value contains "ment" */
div[abc*="ment"] { font-weight: 700; }
/* all elements whose abc value is exactly "element-1" */
div[abc~="element-1"] { color: blue; }
/* all elements whose abc value is exactly "element" or begins with "element" immediately followed by a hyphen */
div[abc|="element"] { background-color: green; }
/* all elements whose abc value starts with "x" */
div[abc^="x"] { background-color: red; }
/* all elements whose abc value ends with "x" */
div[abc$="x"] { background-color: yellow; }
div { margin: 5px 0px; }
<div abc="element-1">Hello World!</div>
<div abc="element-2">Hello World!</div>
<div abc="xElement1">Hello World!</div>
<div abc="xElement2">Hello World!</div>
<div abc="element1x">Hello World!</div>
<div abc="element2x">Hello World!</div>
关于html - CSS [attribute ="value"] 选择器是不必要的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697203/