I have a <select>
:
select:invalid {
color: red;
}
<select required>
<option disabled selected>- please choose -</option>
<option value="1">A</option>
<option value="2">B</option>
</select>
Unfortunately the disabled select is not marked red.
Any idea?
Definition and Usage. The :invalid selector selects form elements with a value that does not validate according to the element's settings. Note: The :invalid selector only works for form elements with limitations, such as input elements with min and max attributes, email fields without a legal email, or number fields without a numeric value, etc.
The :invalid selector selects form elements with a value that does not validate according to the element's settings. Note: The :invalid selector only works for form elements with limitations, such as input elements with min and max attributes, email fields without a legal email, or number fields without a numeric value, etc.
:invalid The :invalid CSS pseudo-class represents any <input> or other <form> element whose contents fail to validate. input:invalid { background-color: pink; } This pseudo-class is useful for highlighting field errors for the user.
The :invalid CSS pseudo-class represents any <form>, <fieldset>, <input> or other <form> element whose contents fail to validate. This pseudo-class is useful for highlighting field errors for the user.
You need to specify value=""
for the first option. Without value=""
, the value of an option is implicitly equal to its text content, meaning it fulfils the required
constraint.
Demo:
select:invalid { color: red; }
<select required>
<option disabled value="" selected>- please choose -</option>
<option value="1">A</option>
<option value="2">B</option>
</select>
The above will make the select + all options red until a value has been chosen.
If you want the options to always be black, just extend the CSS a little:
select:invalid { color: red; }
select option { color: black; }
<select required>
<option disabled value="" selected>- please choose -</option>
<option value="1">A</option>
<option value="2">B</option>
</select>
Try to use option:disabled
.
select option:disabled {
color: red;
}
<select required>
<option disabled selected>- please choose -</option>
<option value="1">A</option>
<option value="2">B</option>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With