CSS 属性选择器速查表,你只要记住这些,精确控制任何 DOM 元素都不在话下。
🔍 CSS 属性选择器速查表
选择器 | 说明 | 示例 | 匹配的元素示例 |
---|
[attr] | 选中含有某属性的元素 | [disabled] | <input disabled> |
[attr="value"] | 属性等于某值 | [type="text"] | <input type="text"> |
[attr~="value"] | 属性值中包含某个“空格分隔的单词” | [class~="btn"] | <div class="btn primary"> |
`[attr | =“value”]` | 属性值是指定值或以其开头、后接 - | `[lang |
[attr^="value"] | 属性值以某值开头(前缀匹配) | [href^="https"] | <a href="https://example.com"> |
[attr$="value"] | 属性值以某值结尾(后缀匹配) | [src$=".jpg"] | <img src="photo.jpg"> |
[attr*="value"] | 属性值包含某个子串 | [title*="apple"] | <div title="green apple pie"> |
🧪 实战示例
input[disabled] {
opacity: 0.5;
}
input[type="password"] {
border: 1px solid red;
}
a[href^="https"] {
color: green;
}
a[href$=".pdf"]::after {
content: " (PDF)";
font-size: 12px;
}
div[class~="important"] {
font-weight: bold;
color: crimson;
}
🔥 使用技巧小建议
场景 | 用法推荐 |
---|
✅ 不想写类名就选中元素 | input[type="number"] 、button[type="submit"] |
✅ 选中特定格式的链接或资源 | [href^="http"] 、[src$=".png"] |
✅ 精准打击含有特殊属性的 DOM | [data-role="modal"] 、[aria-hidden="true"] |
✅ 在没有 class 的第三方组件里加样式 | 用属性选择器很方便! |