:optional

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

:optionallớp giả CSS đại diện cho bất kỳ phần tử <input>, <select> hay <textarea> nào không có thuộc tính required được đặt trên nó.

Try it

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

.req {
  color: red;
}

*:optional {
  background-color: palegreen;
}
<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>

Lớp giả này hữu ích để tạo kiểu cho các trường không bắt buộc phải điền khi gửi biểu mẫu.

Note: Lớp giả :required chọn các trường biểu mẫu bắt buộc.

Cú pháp

css
:optional {
  /* ... */
}

Khả năng tiếp cận

Nếu một biểu mẫu chứa các <input> tùy chọn, các trường bắt buộc phải được chỉ ra bằng thuộc tính required. Điều này đảm bảo rằng những người sử dụng công nghệ hỗ trợ như trình đọc màn hình có thể hiểu được các trường nào cần nội dung hợp lệ để gửi biểu mẫu thành công.

Các trường bắt buộc cũng nên được chỉ ra bằng hình thức trực quan, sử dụng cách thể hiện không chỉ dựa vào màu sắc để truyền đạt ý nghĩa. Thông thường, văn bản mô tả và/hoặc biểu tượng được sử dụng.

Ví dụ

Trường tùy chọn có đường viền màu tím

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:optional {
  border-color: rebeccapurple;
  border-width: 3px;
}

Kết quả

Thông số kỹ thuật

Specification
HTML
# selector-optional
Selectors Level 4
# optional-pseudo

Khả năng tương thích trình duyệt

Xem thêm