試一試
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>
此偽類可用於樣式化非表單提交必需的欄位。
注意: :required 偽類選擇必需的表單欄位。
語法
css
:optional {
/* ... */
}
無障礙
如果表單包含可選的<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:optional {
border-color: rebeccapurple;
border-width: 3px;
}
結果
規範
| 規範 |
|---|
| HTML # selector-optional |
| 選擇器 Level 4 # optional-pseudo |
瀏覽器相容性
載入中…