select2 not responsive, width larger than container

Viewed 46402

I have a problem with the width of a select2 dropdown in my ASP.NET page. When I try to view the page with the Chrome emulator of devices screen, the select2 is larger than the containing div, and on the right it goes out of the screen. I saw with code inspection that it adds automatically a style attribute style="width: 498px;" in the <span class="select2 select2-container select2-container--bootstrap select2-container--below"> element that I did not set anywhere. The only operation that I did is to set $("#ContentPlaceHolderContent_mySelect").select2(); in the document.ready function(). My select2 dropdown is contained in a block:

<div class="form-group">
   <label class="control-label col-md-3">Select structure</label>
   <div class="col-lg-5 col-md-9">
      <select class="form-control" id="mySelect" runat="server"></select>

   </div>
</div>

How can I remove that style="width" option?

8 Answers

This works for me:

$('select').select2({
    width: '100%'
});

and add CSS:

.select2-selection { overflow: hidden; }
.select2-selection__rendered { white-space: normal; word-break: break-all; }

Add to CSS "!important" if you need.

if you are using bootstrap ,use the below style

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

Getting Overflow? Do it with JS also

Using CSS width:100% sometimes get scrolling issue if some elements have overflow property. I would recommend using js also.

Add below js

 $('select').select2({
        width: '100%'
 });

Add below CSS

.select2-selection { overflow: hidden; }
.select2-selection__rendered { white-space: normal; word-break: break-all; }

/*Copied from already given :) */

The <span> with the .select2 class is created by the Select2 plugin just after creation a new select2 on a given <select>.

To make this span.select2 element responsive, we may have some possibilities, such as:

  1. Use a % width (either on the original before creating the select2 element, or in the select2 width configuration option).
  2. Override via CSS (for example when we use @media() queries). Note that this may affect the plugin's functionality or display.

For the 2nd one, we can use the adjacent sibling combinator (+) with the !important on the width value to style our select2's <span>, since normally the select2's span is created and inserted right after our <select>.

An example below:

@media (max-width: 400px) {
  select.my-x-select + span.select2 {
    width: 200px !important;
  }
}

Note: select and span element selectors aren't needed, @media as an example use case.

You don't need to use !important, you just can override it with max-width like:

.select2{
    max-width: 100%;
}

First of all add Select2 class .select2 in select tag and used these CSS

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