Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping select2 element a fixed size with scrolling?

Here is a fiddle for example.

What this example shows is with a normal multiple-select select2 element as the user selects items from the list it will expand down and cause the parent container to expand down. I can't have the parent grow any larger than it is set due to mobile and layout concerns.

How does one set an option to disable expansion of the element or at the very least set the CSS to keep the size of the element and allow the user to scroll?

Code below to prevent linkrot.

HTML:

<form>
  <select class="select-select2" multiple="multiple" data-placeholder="Please choose one or more" data-allow-clear="true" data-close-on-select="false">
    <option>Lorem</option>
    <option>ipsum</option>
    <option>dolor</option>
    <option>sit amet</option>
    <option>consectetur</option>
    <option>adipisicing</option>
    <option>elit sed</option>
    <option>do eiusmod</option>
    <option>tempor</option>
    <option>incididunt</option>
    <option>ut labore</option>
    <option>et dolore</option>
    <option>magna aliqua</option>
    <option>Ut enim ad</option>
  </select>

  <button type="submit">Submit</button>
</form>

js:

$(".select-select2").select2();
like image 310
o_O Avatar asked Sep 25 '15 17:09

o_O


3 Answers

http://jsfiddle.net/8svf11yh/1/

.select2-container .select2-selection {
    height: 60px;
    overflow: scroll;
} 

Or overflow:auto; may be a better choice

like image 162
smcd Avatar answered Nov 06 '22 20:11

smcd


A few refinements to @smcd's version:

.select2-selection--multiple { max-height: 10rem; overflow: auto }

I am using max-height so that it can be smaller if only a few options are selected. Only once it reaches that height does it grow no bigger. As suggested overflow: auto is great as it only uses the scrollbar if needed. Finally I target the --multiple variant of the selector so only selections with multiple options get this styling.

like image 45
Eric Anderson Avatar answered Nov 06 '22 21:11

Eric Anderson


This'll work with the latest select2 plugin:

.select2-results__options {
    height: 60px;
    overflow-y: auto;
}
like image 4
adamj Avatar answered Nov 06 '22 22:11

adamj