Search code examples
csscss-selectors

Change width of the select by text size


how i can make a select with options to have same width like text size?

|Choose your City ▼|  - select
|Option 1|
|option two|
|option abcabcabc|

Result :

|Option 1         ▼|      
|Option two       ▼|
|Option abcabcabc ▼|

But i want to see result like that if i select a specific city

|Option 1▼|      
|Option two▼|
|Option abcabcabc ▼|

Is posible with css to change the width of the option from select?


Solution

  • Well this cannot be done with simple html and css as select has some default width or if you give custom width then also it will not resize according to content.

    Create a different hidden element which is just for keeping text so that you can get the width with jquery and use this small jquery.

    $(document).ready(function() {
      $('#resizing_select').change(function() {
        $("#width_tmp_option").html($('#resizing_select option:selected').text());
        $(this).width($("#width_tmp_select").width());
      });
    });
    #resizing_select {
      width: 50px;
    }
    #width_tmp_select {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <select id="resizing_select">
      <option>1</option>
      <option>two</option>
      <option>abcabcabc</option>
    </select>
    <select id="width_tmp_select">
      <option id="width_tmp_option"></option>
    </select>