Monday, February 23, 2009

I.E. Select Drop Down Cuts Off Using CSS width

The Problem
While setting up an HTML form I ran into an issue where the select box I was using has an option that was really really long. I set the size of the select box to 166px using CSS styles. Except for I.E., Firefox and every other real browser out there handled it just fine. Since the bulk of my users use I.E., I needed to come up with a hack that would not add a lot of code overhead and be maintainable.

Here's what I came up with and it works great!

The Solution

Original Code
<form name="test">
<select name="safetyProgram" id="safetyProgram" style="width:166px;">
<option value="0" selected>No safety program</option>
<option value="1">Cost containment safety program as certified by the state</option>
<option value="2">Formal written safety program with management oversight including inspections, written documentation, on regular meetings</option>
<option value="3">Formal written safety program with regular meeting</option>
<option value="4">Any safety program less than the aformentioned categories</option>
</select>
</form>

Sample




New Code
<form name="test">
<select name="safetyProgram" id="safetyProgram" style="width:166px;position:absolute;z-index:50;" onfocus="this.style.width='auto';" onblur="this.style.width='166px';">
<option value="0" selected>No safety program</option>
<option value="1">Cost containment safety program as certified by the state</option>
<option value="2">Formal written safety program with management oversight including inspections, written documentation, on regular meetings</option>
<option value="3">Formal written safety program with regular meeting</option>
<option value="4">Any safety program less than the aformentioned categories</option>
</select>
</form>


Sample



Note: If you want to constrict the size the drop down option opens out to, simply change the width parameter in the onFocus from auto to say 300px or something. Play with it. You'll get the idea.

And YES, this hack makes the select box float over your other form widgets and text so it doesn't do strange things with the other form elements.

Have a go at it! It did the trick for me. I hope it works for you too!

1 comment:

Brian said...

I left out the absolute positioning and z-index and just used the onfocus and onblur and it still worked. Thanks!