CSS 选择器(属性选择器)
属性选择器
根据属性来为元素设置样式也是常用的场景。
选择器 | 示例 | 描述 |
[attribute] | [target] | 带有 target 属性所有元素 |
[attribute=value] | [target=_blank] | targe 属性 等于"_blank" 的所有元素 |
[attribute~=value] | [title~=thief] | title 属性包含单词 "thief" 的所有元素 |
[attribute|=value] | [title|=hd] | title 属性值为 "hd"的单词,或hd-cms 以-连接的的独立单词 |
[attribute*=value] | a[src*="csdn"] | src 属性中包含 "csdn" 字符的每个 元素 |
[attribute^=value] | a[src^="https"] | src 属性值以 "https" 开头的每个 元素 |
[attribute$=value] | a[src$=".jpeg"] | src 属性以 ".jpeg" 结尾的所有 元素 |
为具有 class 属性的h1标签设置样式
h1[class] {
color: red;
}
...
<h1 class="container">https://blog.csdn.net/weixin_44541438</h1>
约束多个属性
h1[class][id] {
color: red;
}
...
<h1 class="container" id >https://blog.csdn.net/weixin_44541438</h1>
具体属性值设置样式
a[href="https://www.https://blog.csdn.net/weixin_44541438"] {
color: green;
}
...
<a href="https://www.https://blog.csdn.net/weixin_44541438">后盾人</a>
<a href="">csdn</a>
^ 以指定值开头的元素
h2[name^="csdn"] {
color: red;
}
...
<h2 name="Thief">https://blog.csdn.net/weixin_44541438</h2>
<h2 name="csdn.com">csdn.com</h2>
$ 以指定值结尾的元素
<h2 name="thief">https://blog.csdn.net/weixin_44541438</h2>
<h2 name="csdn.com">csdn.com</h2>
...
h2[name$="com"] {
color: red;
}
* 属性内部任何位置出现值的元素
h2[name*="thief"] {
color: red;
}
...
<h2 name="thief">https://blog.csdn.net/weixin_44541438</h2>
<h2 name="https://blog.csdn.net/weixin_44541438">csdn.com</h2>
~ 属性值中包含指定词汇的元素
h2[name~="thief"] {
color: red;
}
...
<h2 name="thief">https://blog.csdn.net/weixin_44541438</h2>
<h2 name="thief web">csdn.com</h2>
| 以指定值开头或以属性连接破折号的元素
h2[name|="thief"] {
color: red;
}
...
<h2 name="thief">https://blog.csdn.net/weixin_44541438</h2>
<h2 name="thief-web">csdn.com</h2>