Make multiple-select to adjust its height to fit o

2019-01-21 21:21发布

Apparently this doesn't work:

   select[multiple]{
     height: 100%;
   }

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

auto doesn't work either, I still get the vertical scrollbar.

Any other ideas?

enter image description here

13条回答
Juvenile、少年°
2楼-- · 2019-01-21 21:37

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-21 21:38

You can only do this in Javascript/JQuery, you can do it with the following JQuery (assuming you've gave your select an id of multiselect):

$(function () {
    $("#multiSelect").css("height", parseInt($("#multiSelect option").length) * 20);
});

Demo: http://jsfiddle.net/AZEFU/

查看更多
欢心
4楼-- · 2019-01-21 21:38
<select id="list">
  <optgroup label="Group">
    <option value="1">1</option>
  </optgroup>
</select>
<script>
  const l = document.getElementById("list")
  l.setAttribute("size", l.childElementCount + l.length)
</script>

https://jsfiddle.net/maars/ou5f3jzy/

查看更多
Bombasti
5楼-- · 2019-01-21 21:45

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">
查看更多
老娘就宠你
6楼-- · 2019-01-21 21:46

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'>
查看更多
唯我独甜
7楼-- · 2019-01-21 21:48

I had this requirement recently and used other posts from this question to create this script:

$("select[multiple]").each(function() {
  $(this).css("height","100%")
    .attr("size",this.length);
})
查看更多
登录 后发表回答