attribute selector 属性选择器
可以设置带有特定属性或属性值的 HTML 元素的样式
[attribute] 选择器用于选取带有指定属性的元素
/*选择所有带有 target 属性的 <a> 元素*/
a[target] {
background-color: hotpink;
}
[attribute=“value”] 选择器用于选取带有指定属性和值的元素
/*选取所有带有 target="_blank" 属性的 <a> 元素*/
a[target="_blank"] {
background-color: yellow;
}
[attribute~=“value”] 选择器选取属性值包含指定词的元素
/*
选取 title 属性包含 "flower" 单词的所有元素
下面会匹配以下属性的元素:title="flower"、title="summer flower" 以及 title="flower new",但不匹配:title="my-flower" 或 title="flowers"
*/
[title~="flower"] {
border: 5px solid yellow;
}
[attribute|=“value”] 选择器用于选取指定属性以指定值开头的元素
/*
选取 class 属性以 "top" 开头的所有元素
值必须是完整或单独的单词,比如 class="top" 或者后跟连字符的,比如 class="top-text",像class="topcontent"这种就不行
*/
[class|="top"] {
background: yellow;
}
[attribute^=“value”] 选择器用于选取指定属性以指定值开头的元素
/*
下例选取 class 属性以 "top" 开头的所有元素
值不必是完整单词
*/
[class^="top"] {
background: yellow;
}
[attribute$=“value”] 选择器用于选取指定属性以指定值结尾的元素
/*
下例选取 class 属性以 "test" 结尾的所有元素
值不必是完整单词
*/
[class$="test"] {
background: yellow;
}
[attribute*=“value”] 选择器选取属性值包含指定词的元素
/*
下例选取 class 属性包含 "te" 的所有元素
值不必是完整单词
*/
[class*="te"] {
background: yellow;
}
设置表单样式
若需为不带 class 或 id 的表单设置样式,属性选择器会很有用
<!DOCTYPE html>
<html>
<head>
<style>
input[type=text] {
width: 150px;
display: block;
margin-bottom: 10px;
background-color: yellow;
}
input[type=button] {
width: 120px;
display: block;
margin-left: 20px;
}
</style>
</head>
<body>
<h1>添加表单样式</h1>
<form name="input" action="" method="get">
Firstname:<input type="text" name="Name" value="Bill" size="20">
Lastname:<input type="text" name="Name" value="Gates" size="20">
<input type="button" value="Example Button">
</form>
</body>
</html>