首页 > 解决方案 > CSS [attribute="value"] 选择器是不必要的吗?

问题描述

我正在学习 CSS 上的 edX 课程之一,它们包括:

[class*='example'] { background-color: orange; }

在 CSS 样式表中。不熟悉那种类型的属性,所以我查了一下。本质上,它只是使用特定的类 [(或 id),取决于特定的属性] 为任何东西添加样式。为什么不添加:

background-color: orange;

到相应的class,或者id,就可以了?我缺少的这种类型的属性是否有重要用途?

标签: htmlcsscss-selectors

解决方案


*in[class*='example']是一个选择器,它检索包含在 class-name 中的所有元素,而example不仅仅是带有 class-name 的元素example

因此,[class*='example']将针对以下所有方面:

<div class="iamanexample"></div>
<div class="example"></div>
<div class="whereisyourexample"></div>

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


推荐阅读