:required

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

:required CSS 伪类表示任何设置了 required 属性的 <input><select><textarea> 元素。

试一试

label {
  display: block;
  margin-top: 1em;
}

.req {
  color: red;
}

*:required {
  background-color: gold;
}
<form>
  <label for="name">Name: <span class="req">*</span></label>
  <input id="name" name="name" type="text" required />

  <label for="birth">Date of Birth:</label>
  <input id="birth" name="birth" type="date" />

  <label for="origin"
    >How did you find out about us? <span class="req">*</span></label
  >
  <select id="origin" name="origin" required>
    <option>Google</option>
    <option>Facebook</option>
    <option>Advertisement</option>
  </select>
  <p><span class="req">*</span> - Required field</p>
</form>

这个伪类对于在表单提交前突出显示必须包含有效数据的字段很有用。

注意: :optional 伪类选择可选的表单字段。

语法

css
:required {
  /* ... */
}

无障碍

必填的 <input> 应该应用 required 属性。这将确保使用辅助技术(如屏幕阅读器)导航的人能够理解哪些输入需要有效内容以确保成功提交。

如果表单还包含可选输入,则应使用不完全依赖颜色来传达意义的处理方式,在视觉上标明必填输入。通常使用描述性文本和/或图标。

示例

必填字段具有红色边框

HTML

html
<form>
  <div class="field">
    <label for="url_input">Enter a URL:</label>
    <input type="url" id="url_input" />
  </div>

  <div class="field">
    <label for="email_input">Enter an email address:</label>
    <input type="email" id="email_input" required />
  </div>
</form>

CSS

css
label {
  display: block;
  margin: 1px;
  padding: 1px;
}

.field {
  margin: 1px;
  padding: 1px;
}

input:required {
  border-color: maroon;
  border-width: 3px;
}

input:required:invalid {
  border-color: #c00000;
}

结果

规范

规范
HTML
# selector-required
选择器 Level 4
# required-pseudo

浏览器兼容性

另见