CSS 属性选择器速查表,你只要记住这些,精确控制任何 DOM 元素都不在话下。
/* 所有禁用的 input */
input[disabled] {
opacity: 0.5;
}
/* 所有 type 为 password 的 input */
input[type="password"] {
border: 1px solid red;
}
/* 所有 href 以 https 开头的 a 链接 */
a[href^="https"] {
color: green;
}
/* 所有 href 以 .pdf 结尾的 a 链接 */
a[href$=".pdf"]::after {
content: " (PDF)";
font-size: 12px;
}
/* class 属性里含有 "important" 这个词的元素 */
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 的第三方组件里加样式 | 用属性选择器很方便! |