Select2: Issues with responsive width

Created on 23 Apr 2015  ·  34Comments  ·  Source: select2/select2

Unless I am missing something (I apologize if I have), select2 is not fully responsive. Look at this code:

    <div class="col-sm-6">
        <div class="form-group">
            <label>Submit to</label>
            <select class="form-control" id="SubmitQueue" name="SubmitQueue">
                <option value="1">Subsequent Civil</option>
                <option value="2">Subsequent Criminal</option>
                <option value="3">Judge Order - Civil</option>
                <option value="4">Review Sign</option>
                <option value="5">Subsequent Domestic Family</option>
                <option value="6">Judge Order - Criminal</option>
            </select>
        </div>
    </div>

The original select has 100% width from the form-control class. Select2 is creating a fixed width container. Thus, when I resize the window the select2 container does not resize as it should since the col-sm-6 class is a percentage.

So did I miss something in my initialization or is this an issue?

EDIT: OK. I looked throught the code and I noticed that the _resolveWidth doesn't even attempt to get a percentage width from CSS and only works with an inline style. I can live with that. How did it work in 3.5.2 without the inline style?

4.x enhancement styling

Most helpful comment

Temporary workaround is to specify width in the init() I can get away with this as all mine happen to work fine 100% width.

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

All 34 comments

What I was seeing, is that the 100% width is being converted into 100px. Hence the loss in responsiveness. Are your element initially hidden ? I was setting the option width to 100%
for example: options.width = '100%';
and additionally using the following to work-around some of the issues. I never got the place-holder text working on long strings, they get truncated at approx 100px. Manually clearing the selection worked, but I never got a programmatic solution.
//// Fix a select2 ver 4.x issue with widths on initially hidden elements
if ($(element).not(':visible')) {
$('.select2-search__field').width("100%"); // The placeholder text needs help as well.

No, they are not initially hidden. I will look at that options.width to see if it works for me.

I've found that if you have select 2 in a hidden div, when you later reveal that div the width is wrong, is there a method to re-initialise the positioning?

Temporary workaround is to specify width in the init() I can get away with this as all mine happen to work fine 100% width.

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

Also having this issue. Have a select2 (v4) in a Bootstrap v3 accordion panel that is closed on page load. When I expand the panel for the first time, the width of the placeholder text is set to 100px even though the select2 element is much wider based on the markup and the browser window size. After I enter one or two values and then delete them, the placeholder displays correctly.

My HTML markup is
<select id="mySelect" class="form-control" style="width: 80%;" multiple="multiple"></select>

The select2 is getting remote data via Ajax, in case it matters.

Also using the bootstrap theme for select2.

This is happening on a desktop (IE 11), and I am not changing the display/window size, so I don't think this can be dismissed by saying select2 is not responsive.

Setting width to 100% as recommended above does not seem to fix this.

I have the same problem using https://github.com/select2/select2-bootstrap-theme
js

    // Select2
    $('#mySelect').select2({
        theme: "bootstrap",
        placeholder: 'Categorias...',
        allowClear: true,
        tags: true,
        maximumSelectionLength: 3,
        width: '100%'
    });

html

<div class="form-group">
  <label class="sr-only" for="categorias">Categorias</label>
  <select id="mySelect" class="form-control" style="width: 100%;" multiple="multiple">
    <option>Tour de Compras</option>
    <option>Guia</option>
    <option>Internacional</option>
    <option>Desayuno</option>
    <option>Traslados</option>
  </select>
</div>

animacion

screenshot from 2016-04-16 17 50 52

I have problem with select tag .i.e when i resize the windows , it doesn't work, doesn't show the options list.

I use the select2-bootstrap-theme and with this simple hack
$(self._select2).parent().find(".select2-container").css('width', ''); all is working fine on my side.

why not allow a an option width:'none' that doesn't set the width on :

  Select2.prototype._resolveWidth = function ($element, method) {
    var WIDTH = /^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;
    // +++
    if (method == 'none') {
        return null;
    }
    // end +++

    if (method == 'resolve') {
      var styleWidth = this._resolveWidth($element, 'style');

      if (styleWidth != null) {
        return styleWidth;
      }

      return this._resolveWidth($element, 'element');
    }

Only the css will be responsible on width on the select2 container.

Hello, I add custom.css

@media screen and (max-width: 767px) {
    .select2 {
        width: 100% !important;
    }
}

and solved

I tried adding the media query that seanjamu suggested but it's still not working. I'm lost what is the real solution for not breaking on window resize with bootstrap? it still breaks even on the demo page when you zoom in and out. Also using the theme above didn't solve it.

Any advice would be really appreciated. Thx.

Using Bootstrap theme I have the same issue. @seanjamu 's CSS override works well enough for now, but why on earth are they defining the width of an input using an inline style with pixels?

@tchiotludo props for this method. I think it would be nice to have this implemented for "more advanced" users. I had css widths set since select2 3.5 and now I either need to either add !important to every class (which is lame) or have a width: 'none' solution, which is pretty neat.

@kevin-brown could you consider this?

@tchiotludo solution worked for me with Angular 2.

this.element.nativeElement.parent().find(".select2-container").css('width', '');

It was probably not the case when @tchiotludo commented on his lines of code, but now you can just pass a width: '' (empty string) parameter to your select2 config and no width will be added. You will need to handle the width in your css code though, so add a width:100% or whatever you need depending on the screen resolution.

To be more precise, here is how I call my code:
$('.my-select').select2({ theme: 'custom', minimumResultsForSearch: -1, width: '' });

In the HTML5 data-* attribute, you can solve this by setting data-width:

<select id="customer" name="customer" class="form-control select2"
    data-width="100%" required>
</select>

For those experiencing truncated placeholder with v4 of select2, here is a working solution by @labster found here:
.select2-selection--multiple .select2-search--inline .select2-search__field { width: auto !important; }

Thanks @tchiotludo , your comment was really useful. It seems like the problem is select2-bootstrap-theme setting a fixed with on the select container; this solves the problem for me:

$(function() { 
  $('#controlID').select2({ theme: 'bootstrap' }); 
  $('#controlID').parent().find('.select2-container').css('width', ''); 
});

Hello all! It's been a while since I actively worked on and with select2-bootstrap-theme (and with select2 itself for that matter), so please take all my comments with a grain of salt.

As far as I recall things, the theme does __not__ set a fixed width on the select2 container. Actually, I'm pretty sure about this; the theme merely defines CSS. What you are seeing is what I believe to (still) be Select2's default behavior – set the width of the select2 container to the width of the original <select> element it was initialized on.

@demedos I'd love to take a look at this if you can show me where select2-bootstrap-theme does set a width on the select2 container.

FWIW, the demonstration pages for select2-bootstrap-theme use the same (or _similar_) workaround people are recommending here, which is setting width: null, which will disable the default behavior I mentioned above: https://github.com/select2/select2-bootstrap-theme/blob/8f833863dc3bf5c0d8d7113a8da43acb2c7c7c91/docs/_layouts/default.html#L541

That should have been documented – I apologize that it was not.
Please help out and improve the documentation if you find the time to do so!

That said, the last time I checked Select2 still had problems fully supporting responsive designs. One thing I seem to remember is related to .select2-search__field (as mentioned in https://github.com/select2/select2/issues/3278#issuecomment-298035731).

@fk I'm sorry, I didn't have the time to check your source code and the problem seemed to have happened just right after I installed your theme, but apparently I was wrong. Thank you for pointing us out!

@demedos No worries! 🤗 ❤️

Hopefully I will have some time next week to get back on track with select2 a little and at least update the documentation and close that other issue in the select2-bootstrap-theme repo.

@fk I've set up a temporary chat room for Select2 in https://chat.userfrosting.com/channel/select2, if you want to talk about any ideas you have in real time. I'm thinking about setting up a dedicated Select2 chat server as well, to take some of the pressure off of the issue tracker - would be interested in hearing your thoughts on that.

I do the following to accomplish @alexcroox's suggestion in a global scope:

$.fn.select2.defaults.set( "width", "100%" );

You're the real MVP @alexcroox

Thanks @alexcroox! My instance was with the select being initially hidden, then upon display the width would reset to 100px versus what I set as 100%. It's a bit of a shotgun solution, but hey it works for my case.

Update:
Found that if you explicitly set the style/width of the select2 will render properly regardless if initially hidden in a div.

We don't have immediate plans to provide this. We are focused to fix some major UI bugs (that are majority of issues and PR's). But if you open a PR with unit tests, I will be glad to review and approve if everything is ok :+1:

correctly fixed with sass code (for long placeholder) :

.select2-selection--multiple{
    .select2-selection__rendered{
        li:first-child{
            &.select2-search{
                width: 100% !important;
                input{width: 100% !important;}
            }
        }
    }
}

Finally Solved this issue,
previously i was overriding the styling using JQuery but it was not able to find that element.
As a solution what is did is

-> Create a js function

function chsize() {
$(".select2-container--default").css("width","100%"); // this onw works only on Desktop
$("head").append($("")); // this will work everyehere whether it is Mobile, Desktop
}

-> Call the function on page load inside body tag

-> Here is my CSS file override.css
.select2-container--default
{
width: 100%;
}

Enjoy :)

Using @alexcroox method I added the following CSS to my page

.select2 { width: 100% !important; }

and removed placeholder option during initialization in JavaScript. This is the only hack which has worked for me so far after spending many hours searching for a work around using CSS and JavaScript. I am using 4.0.2 version of select2.

Hi, I had same issue in table element and managed to solve the issue with this code :

                td_element.appendChild(select_element);

                var selectWidth = document.getElementById('select_element_id').clientWidth;

                $("#select_element_id").select2({
                    placeholder: "Placeholder..",
                    allowClear: true,
                    width: selectWidth.toString()+'px'
                });

I had the same issue as angular. I added
::ng-deep .select2-container{
display:block !important;
width: 100% !important;
}

and it's working

In the HTML5 data-* attribute, you can solve this by setting data-width:

<select id="customer" name="customer" class="form-control select2"
    data-width="100%" required>
</select>

This is a better solution than using css width: 100%, because that might impact the outer html DOM, as it did with my project. If I used css and clicked on the select button, I could scroll on the x and x axis. Using data-width="100%" on the element, that issue was resolved and still gave the same styling as with css.

In the HTML5 data-* attribute, you can solve this by setting data-width:

<select id="customer" name="customer" class="form-control select2"
    data-width="100%" required>
</select>

This was by far the best solution with minimal cognitive load. Thumbs up

This was by far the best solution with minimal cognitive load. Thumbs up

Thanks!

Was this page helpful?
0 / 5 - 0 ratings