Search code examples
htmlcssjquery-select2bootstrap-4jquery-select2-4

Select2 multiple select shrinks inside bootstrap4 inline form


Below is a snippet demonstrating my issue. The problem is that the field gets really small whenever I type in it.

$(function() {
  $("select").select2({
    placeholder: "Select a word",
    width: "100%"
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<link href="https://select2.github.io/select2-bootstrap-theme/css/select2-bootstrap.css" rel="stylesheet"/>

<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.js"></script>
<div class="container">
<form class="form-inline">
<div class="form-group row">
<div class="col-sm-12">
<select multiple="multiple" name="word" id="word">
  <option value="1">A really long string</option>
</select>
</div>
</div>
</form>
</div>

How do I prevent the field from shrinking?


Solution

  • The shrinking is to do with the

    width: 100%

    The select is attempting to derive it's width from the parent container but at no point do any of the parents have a specified width.

    https://jsfiddle.net/wcy2L3pj/

    I put your code into that fiddle and added style="width: 100%;" to the row parent and the shrinking stops. If you experiment with moving that width definition you'll see that on every other element, using a percentage value doesn't stop the shrinking.

    However, swap the style="width: 100%;" for style="width: 250px;", a specific pixel value, and the shrinking problem stops. This because there is a defined concrete value that the Select2 can draw from with the width: 100% set in its initialisation.