Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select dropdown fit width to current selection

Is there a non-JavaScript way (or at most a native JavaScript way) of making a select element's width match the current selection? When clicked on, the dropdown will be the width of the longest option, but the select itself should only take up as much space as it needs.

I am trying to put a select element inline with some text, so something with a fixed width like this looks funny:

<p>you are currently viewing
the <select style="width:200px;"><option>Awesome</option></select>
option</p>

It will end up looking like you are current viewing the Awesome ▼ option. I want the width to fit the selection, so it looks smooth like you are current viewing the Awesome ▼ option.

like image 894
tau Avatar asked Nov 11 '22 09:11

tau


1 Answers

I had the same issue a few months ago, but I couldn't find a pure CSS-HTML solution. However, I've found a good example in js with jQuery ,it's not heavy at all : http://jsfiddle.net/kn9DF/77/

<script>
   function setSelectWidth() {
       var sel = $('#sel');
       $('#templateOption').text( sel.val() );
       sel.width( $('#template').width() * 1.03 );
   }
</script>
like image 92
potashin Avatar answered Nov 15 '22 03:11

potashin