試一試
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 |
瀏覽器相容性
載入中…