[html] How to control the width of select tag?

I have a list of countries, some with a very long name:

<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>

By default, the select box would be as long as the longest option in the list. I want to create a select box such that it exhibits the default behaviour when viewed from a wide browser window, but fit in nicely to 90% of container width when viewed from a narrow browser window, smaller than the length of the longest option.

I tried min-width: 90%;, but it didn't work. Can this be done by CSS styling alone?

This question is related to html css

The answer is


Add div wrapper

<div id=myForm>
<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</div>

and then write CSS

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

Hope this will help.


You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.

You need to use max-width instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.