存在性和值完全匹配
Coddy CSS 选择器 课程的第 12 课,共 15 课。
在这节课中,你将学习属性存在选择器和精确值选择器。属性选择器用于根据属性是否存在,或属性的精确值来选择元素。
属性存在选择器:
属性存在选择器会选中具有特定属性的元素,无论该属性的值是什么。它使用方括号表示,方括号中写入属性名称。
示例:
/* 选中所有带有 "target" 属性的元素 */
[target] {
color: blue;
}精确值选择器:
精确值选择器会选中具有特定属性和特定属性值的元素。它使用方括号表示,方括号中写入属性名称、等号和所需的值。
示例:
/* 选中 "data-type" 属性值为 "important" 的元素 */
[data-type="important"] {
font-weight: bold;
}代码示例:
HTML:
<p>This is a <span target="link">link</span> element.</p>
<p data-type="important">This is an important paragraph.</p>CSS:
[target] {
text-decoration: underline;
}
[data-type="important"] {
color: red;
}这些示例展示了 CSS 属性选择器如何根据属性是否存在或属性的精确值来选择元素,并为这些元素应用相应的样式。
挑战
简单你需要使用属性选择器为一个简单的 HTML 表单设置样式。
使用属性选择器应用以下样式:
- 为属性
type设置为 "text" 的输入字段添加green边框。 - 将属性
type设置为 "email" 的输入字段的背景颜色改为lightblue。 - 将属性
type设置为 "password" 的输入字段的文字颜色设为red。
亲手试试
<!DOCTYPE html>
<html>
<head>
<title>Styled Form</title>
<style>
/* Apply styles to form fields based on attribute values */
</style>
</head>
<body>
<form>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
<label for="password">Password:</label>
<input type="password" name="password" id="password">
<input type="submit" value="Submit">
</form>
</body>
</html>
CSS 选择器中的所有课
自己练习: Web 在线编辑器