Make multiple-select to adjust its height to fit options without scroll bar

前端 未结 16 993
说谎
说谎 2020-12-24 03:59

Apparently this doesn\'t work:

   select[multiple]{
     height: 100%;
   }

it makes the select have 100% page height...

auto

相关标签:
16条回答
  • 2020-12-24 04:48

    Old, but this will do what you're after without need for jquery. The hidden overflow gets rid of the scrollbar, and the javascript makes it the right size.

    <select multiple='multiple' id='select' style='overflow:hidden'>
    <option value='foo'>foo</option>
    <option value='bar'>bar</option>
    <option value='abc'>abc</option>
    <option value='def'>def</option>
    <option value='xyz'>xyz</option>
    </select>
    

    And just a tiny amount of javascript

    var select = document.getElementById('select');
    select.size = select.length;
    
    0 讨论(0)
  • 2020-12-24 04:48

    To remove the scrollbar add the following CSS:

    select[multiple] {
        overflow-y: auto;
    }
    

    Here's a snippet:

    select[multiple] {
      overflow-y: auto;
    }
    <select>
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select>
    
    <select multiple size="3">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select>

    0 讨论(0)
  • 2020-12-24 04:50

    select could contain optgroup which takes one line each:

    <select id="list">
      <optgroup label="Group 1">
        <option value="1">1</option>
      </optgroup>
      <optgroup label="Group 2">
        <option value="2">2</option>
        <option value="3">3</option>
      </optgroup>
    </select>
    <script>
      const l = document.getElementById("list")
      l.setAttribute("size", l.childElementCount + l.length)
    </script>
    

    In this example total size is (1+1)+(1+2)=5.

    0 讨论(0)
  • 2020-12-24 04:50

    The way a select box is rendered is determined by the browser itself. So every browser will show you the height of the option list box in another height. You can't influence that. The only way you can change that is to make an own select from the scratch.

    0 讨论(0)
  • 2020-12-24 04:53

    You can do this using the size attribute in the select tag. Supposing you have 8 options, then you would do it like:

    <select name='courses' multiple="multiple" size='8'>
    
    0 讨论(0)
  • 2020-12-24 04:56

    I know the question is old, but how the topic is not closed I'll give my help.

    The attribute "size" will resolve your problem.

    Example:

    <select name="courses" multiple="multiple" size="30">
    
    0 讨论(0)
提交回复
热议问题