CSS 伪类 :optional 可用于选择和样式化表单元素,例如 <input>、<select> 或 <textarea>,这些元素对于用户输入不是必需的,或者您可以说没有设置必需的属性。
可访问性问题:当表单列出一些可选的 <input>字段时,它应使用必填属性清楚地指示必填字段。这将有助于那些使用辅助技术(例如屏幕阅读器)导航的人了解成功提交表单的必填字段。
除了必填属性外,必填字段还应使用一些描述性文本或图标来表示,以便更清楚地传达必填信息。
除了必填属性外,必填字段还应使用一些描述性文本或图标来表示,以便更清楚地传达必填信息。
语法
:optional {
/* ... */
}
CSS 伪类 :optional
下面是一个示例:伪类 :optional
在以下示例中,将 :optional 伪类应用于未被赋予必需属性的输入元素。3px 宽的蓝色边框 css 样式将应用于可选的输入元素。
<html>
<head>
<style>
label {
display: block;
margin: 1px;
padding: 1px;
}
.field {
margin: 1px;
padding: 1px;
}
input:optional {
border-color: blue;
border-width: 3px;
}
label.required::after {
content: "*";
color: red;
}
button {
background-color: green;
color: white;
}
form {
border: 3px solid black;
}
</style>
</head>
<body>
<form>
<div class="field">
<label for="name" class="required">Name:</label>
<input type="name" id="name" required/>
</div>
<div class="field">
<label for="age">Age: (optional)</label>
<input type="age" id="age" />
</div>
<div class="field">
<label for="feedback">Feedback: (optional)</label>
<input type="feedback" id="feedback" />
</div>
<div class="field">
<button type="">Submit</button>
</div>
</form>
</body>
</html>