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 very hard 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’d recommend you to avoid building custom form elements at all cost. If you absolutely have to use a custom styled solution, use a battle tested library instead of rolling your own.
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 realise that the HTML select element does not support the placeholder attribute, I just assumed it does. The next thing I tried was 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 (and maybe even in Internet Explorer) but in WebKit and Blink based browsers, this does not work either.
After playing around and noticing that you can change the color of the select element itself, I worked on the idea of setting the select elements color 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.
Assuming that select fields are either always required or we are able to provide a default value for optional select fields, is an assumption which might not hold true all of the time.