CSS 的 属性选择器
CSS 的 属性选择器(Attribute Selectors) 允许你根据元素的 属性名称 或 属性值 来选择元素,从而实现更精准的样式控制。它常用于表单、链接、自定义数据属性等场景。
1.选择具有特定属性的元素
[attribute] {/* 样式规则 */
}
2.选择具有特定属性和属性值的元素
[attribute=value] {/* 样式规则 */
}
3.选择具有特定属性以特定值开头的元素
[attribute^=value] {/* 样式规则 */
}
4.选择具有特定属性以包含特定值的元素
[attribute$=value] {/* 样式规则 */
}
5.选择具有特定属性以包含特定值的元素:
[attribute*=value] {/* 样式规则 */
}
以下是使用属性选择器的示例,展示如何将样式应用到html页面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>[title]{color: red;}a[href^="https://"] {text-decoration: underline;}[class*="button"]{background-color: gray;}</style>
</head>
<body><h1 title="hi">hi world</h1><p>no title 段落</p><a href="http://www.example.com">example</a><a href="http://www.example.com">example</a><buton class="btn"> button1</buton><buton class="button-primary"> button2</buton>
</body>
</html>
在以上的示例中,我们使用属性选择器将样式应用到具有特定属性的元素