Simplest Method to Custom Styling of The SELECT Elements

How it works

The solution works in a way that it dynamically adds an additional SPAN element positioned absolutely below the SELECT element. This SPAN has a custom graphic that we want to apply. SELECT element’s opacity is set to zero so it is not visible but it’s clickable. Since the SELECT element is not visible, what we see actually is the SPAN below.

This solution doesn’t style the OPTION dropdown, only the default appearance of the SELECT element but it is very applicable.

Important thing to remember: this trick relies heavily on absolute positioning. Newly created SPAN element will position itself in relation to parent element (DIV in my case). If you have other stuff inside the parent element, things like text, labels etc. make sure that you position the newly created SPAN accordingly.

The script

Here is the entire script:

Script, line by line explained:

Script executes on DOM load.

Had some issues with transparency in Opera so I decided not to support Opera for this trick.

What follows will apply to every SELECT element with the class name select

Each SELECT element should have TITLE attribute set to whatever we want to show as a default value of the drop down. We are storing the value of the TITLE attribute in a variable for further usage.

Checking if any of the options is selected by default. If it is we will use it as a default value. If not, we are using the previously stored TITLE attribute value.

For each of the SELECT elements we are setting the z-index to anything above the value of 1, opacity to zero, and we’re also removing the default styling for Safari.

We are then adding a SPAN element that have background image set in CSS and is placed exactly below the SELECT element.

With every change of value for the SELECT elements we are updating the SPAN element inner text.

HTML/CSS source code

Just as a script, proper markup and CSS is very important to make this to work. SELECT elements needs to be wrapped inside a parent element (DIV in my case) that has a position property set to relative, so the newly created SPAN can be properly positioned.

This is the markup for the SELECT element:

Note the TITLE attribute. Script will use it as a default value.

CSS looks like this (some comments included):

Custom styling for select elements

Take a look at the demo or
Download Files

One thought on “Simplest Method to Custom Styling of The SELECT Elements

Leave a Reply

Your email address will not be published. Required fields are marked *