Wednesday, January 23, 2013

Styling HTML Selects (Dropdown Hack)

One of the top gripes I have with current web standards is an almost complete lack of support for styling HTML selects with anything other than a few colors or size modifications in IE or Firefox.

Recently, I had a project where I wanted a fresh look to all my input forms, making them appear as single gray lines like you would find on a pen-and-paper form.

Here is the initial set up for the project:
With initial styling, we end up with this:

Looking good! In fact, it will be perfect if we can just get rid of that darn down arrow to make the inputs look identical!

In chrome, this is a simple matter of adding one line to our flat class: -webkit-appearance: none

This line will tell any webkit browser to ignore the default styling they usually apply to controls and instead use the one I've defined. For selects, this has the effect of completely removing the dropdown arrow, leaving me with exactly what I want:
Chrome with -webkit-appearance:none

However, this does not address IE and Firefox, neither of which are webkit. Unfortunately, there is no way to simply style away the down arrow in these two browsers. So, what now? This is where things get annoying. In a perfect world, there would be a selector for all browsers such as chrome has, but because there is not, you might as well not even use it in chrome, since this hack for Firefox and IE will do the trick in chrome as well.

First we need to alter the markup. 

...and the css...

The select itself needs to go inside of a span. This span will have overflow:hidden, and a width smaller than the width of the select. This means the the down arrow is still technically there, but is running off the right edge of the span and is thus invisible to the user. We will also set the container span's height to something smaller than the height of the select, so that the top border of the select is now invisible. This is because IE7 is a pain in the butt and likes to ignore "border: none" on select objects.

Manipulating the padding and margins around a bit, and adjusting width as needed, gives us a way to have consistent select of any style or, in my case, a boring gray line that I think looks awesome.

The last three lines are dropdowns!
Gregor the Bold, rides again! kye yah!

Final Code