Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style invalid <select> using :invalid

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?

It's not the option I like to style, I like to style the select!

like image 278
Grim Avatar asked Mar 15 '18 10:03

Grim


People also ask

What is an invalid selector in HTML?

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.

What is an invalid form element?

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.

What does invalid input mean in CSS?

: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.

What is an invalid CSS pseudo-class?

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.


2 Answers

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>
like image 58
Peter B Avatar answered Sep 18 '22 17:09

Peter B


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>
like image 32
htshame Avatar answered Sep 18 '22 17:09

htshame