Tuesday, May 27, 2008

Styling <select> tag widths

OK, there are a gadzillion web pages on the web already complaining about IE (pick any version up to 7) and the way it handles the <select> tag. My main problem was that I wanted to give the dropdown list a fixed width, so it could fit within the bounds of a box on the screen, but I cannot control the length of the items in the list, so I need to be able to show the user the entire text when trying to select the value.

My first attempt simply fixed the width CSS property. As you can see the result was perfect in Firefox:


However in IE7 (even with the new <select> tag) it just truncates the values:


When testing this with actual client data we realised they had values that differed in the last couple of characters only (e.g. "Training Course 001" and "Training Course 002"., but much longer).

So I went ahead and removed the width CSS property from the relevant class, and this is what we got:


The problem is now that the remove icon is covered up, preventing the user from using it until they have selected something from the list and it replaces the edit box with the read-only one (like below):


I looked for ages to try and find good cross-browser safe ideas for how to handle this, and briefly tried using JavaScript to trap the onclick and onblur events and re-size the field at that point. Ugly. Buggy. And just plain nasty as a future-safe solution. I even tried setting width on <option> tags using CSS, but while that worked in Firefox it still failed in IE.

So after much trawling for help, and revising much of what I already knew about styling forms in CSS, I came across this gem of a solution. Setting the title attribute on the <option> tags allows them to show a tooltip in IE7 that shows the user the full text value of each option:


1 comment:

  1. Anonymous3:48 am

    This is perfect. I was struggling for a way to fix this. Thanks!