Select2 not calculating `resolved` width correctly if select is hidden

I am using Twitter bootstrap and the fantastic Select2 plugin.

These are working great, I realized you need to set {width: 'resolve'} when initiating Select2 otherwise it looks messed up!.

But I am having an issue with one of my selects, as you can see in the image below, the Referee Type select has an incorrect width.

This is caused due to this field being initially hidden, and only becoming visible if Referee is selected in the Group field.

So, how can I fix this?

Inputs


Select 2 is smart enough to recalculate it's size if only you set it in the select tag. Like so:

<select style="width: 100%"></select>

CSS formatting on classes would not work!

Read more in "Responsive design - Percent width"


You can set the width in the <select> element like so:

<select style="width:260px">

Until you find the desired width that you're looking for. In fact, the examples on the official select2 plugin site are done in this way.

However, if you're intent upon staying away from inline styles, you can always simply override select2's CSS and target the resulting container.

.select2-container {
  width: 260px;
}

I solved my similar problem with simple CSS:

.select2-container {
    width: 100% !important;
}

Instead of invoking select2() on the Referee Type when the page loads, invoke select2 after showing Referee Type for the first time. This way, the select will be visible (with a proper width), and the 'width': 'resolve' option should work. If you provide a small jsfiddle example it would be easier to point this out.


Set the style property of select element with width 100%

<select class="js-example-responsive" style="width: 100%"></select>

See Responsive design - Percent width