Styling native HTML form fields – especially select fields – with CSS has always been a little tricky. Recently I was confronted with the task of creating a select field with a placeholder value so that the select field blends in nicely with other form fields on the page.
Most of the time, this is a pretty bad idea. It is tough to get accessibility right when building a custom form element. Many of those custom-built select form fields do not work with screen readers at all or are very hard to use on mobile devices.
I recommend you to avoid building custom form elements at all costs. If you have to use a custom-styled solution, use a battle-tested library instead of rolling your own.
Styling a Disabled Option Element
In my case, it was not necessary to swap the native HTML select field with a fake select field. The problem at hand is how to display a placeholder inside a select field.
At first, I didn’t realize that the HTML select element does not support the placeholder attribute; I just assumed it does. Next, I tried using a
disabled but default selected option element and setting the font color to the same grey as the input placeholder element. And this works in Firefox, but in WebKit and Blink based browsers, this does not work either.
Pure CSS Solution
After playing around and noticing that you can change the color of the select element itself, I worked on the idea of setting the color of the select element to placeholder grey as long as a disabled option is selected and changing the color to the default color as soon as the value changes.
required attribute and the
:invalid pseudo-class to achieve the effect I was looking for.