Set width of dropdown element in HTML select dropdown options

Greg Zwaagstra picture Greg Zwaagstra · Nov 9, 2009 · Viewed 229.2k times · Source

I am working on a website that involves automatically populating a select box using a PHP script. This all works fine except the problem is that what I am using to populate the text box have very long titles (they are journal articles and presentation titles). The dropdown box extends to the width of the longest element, which stretches off the edge of the screen, therefore making the scrollbar impossible to reach. I have tried various methods of trying to manually set the dropdown box using CSS to a particular width, but so far to no avail. The best I have accomplished it to set the Select box to a certain width but the dropdown menu itself is much, much wider.

Any tips on this would be greatly appreciated.

EDIT:

It turns out that the following CSS line works in all of the primary browsers except for Google Chrome (which is what I was testing the page in). If a solution for Chrome is known, that would be good to know about.

select, option { width: __; }

Answer

None picture None · Dec 9, 2011

I find the best way to handle long dropdown boxes is to put it inside a fixed width div container and use width:auto on the select tag. Most browsers will contain the dropdown within the div, but when you click on it, it will expand to display the full option value. It does not work with IE explorer, but there is a fix (like is always needed with IE). Your code would look something like this.

HTML

<div class="dropdown_container">
  <select class="my_dropdown" id="my_dropdown">
    <option value="1">LONG OPTION</option>
    <option value="2">short</option>
  </select>
</div>

CSS

div.dropdown_container {
    width:10px;
}

select.my_dropdown {
    width:auto;
}

/*IE FIX */
select#my_dropdown {
    width:100%;
}

select:focus#my_dropdown {
    width:auto\9;
}