html - CSS [attribute="value"] 选择器是不必要的吗?
问题描述
我正在学习 CSS 上的 edX 课程之一,它们包括:
[class*='example'] { background-color: orange; }
在 CSS 样式表中。不熟悉那种类型的属性,所以我查了一下。本质上,它只是使用特定的类 [(或 id),取决于特定的属性] 为任何东西添加样式。为什么不添加:
background-color: orange;
到相应的class,或者id,就可以了?我缺少的这种类型的属性是否有重要用途?
解决方案
*
in[class*='example']
是一个选择器,它检索包含在 class-name 中的所有元素,而example
不仅仅是带有 class-name 的元素example
。
因此,[class*='example']
将针对以下所有方面:
<div class="iamanexample"></div>
<div class="example"></div>
<div class="whereisyourexample"></div>
而.example
or[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>
推荐阅读
- opencart-3 - 已编入索引,但已被 robots.txt 阻止”:这是什么意思以及如何修复?
- python-3.x - 如何从 python 应用程序 SSO 到目录服务器
- python - 只有第一个 IF 语句有效!所有其他 IF 不工作
- react-native - 反应原生;Facebook 登录错误:未定义不是对象(login-WithReadPermissionAsync)
- cors - 如何为 CORS 配置 KeyCloak?
- python - Python TLS 客户端代码给出 Wrap Socket 意外关键字错误
- java - 如何创建和存储从 Java GUI 获取输入的对象?
- python - 如何使用 mysql 连接器创建 sql 连接以通过 df.to_sql() 写入数据库
- python - 将多维 numpy 数组中的列提高到 2 次方
- sqlite - QSortFilterProxyModel 仅对获取的数据进行排序