Responsive Select2 In Html
For the past few years, I have been using Select2 to build effective dropdown menus in Bootstrap. Recently, I spent some time trying to make it responsive, but it didn't perform as well as expected out of the box.
Here is a useful thread that helped me get it working:
https://github.com/select2/select2/issues/3278
Using the tricks in that thread, you can make the dropdown responsive, which is quite useful. However, something was still missing for my use case.
In my implementation, I needed a feature where the dropdown sits in a small space by default, but expands to use the full width when a user interacts with it.
So I inspected the HTML that the plugin generates. I noticed that the Select2 plugin inserts some div elements immediately after the select element. If you try to set the width on the Select2 container either before or after calling the Select2 initializer, it will not work correctly.
The solution is to write CSS that targets the generated div. For example:
.select2-container{
width: 90px;
}
This will constrain the Select2 element to 90px. That's how you modify the CSS of the generated HTML. But wait — what if you want the dropdown to expand to a wider width when the user clicks on it? I inspected further and found that the plugin generates another div to display the search bar and the options list.
The dropdown element has the following CSS classes:
select2-dropdown select2-dropdown—below
So, if you want the dropdown panel to be wider when opened, you target that container. For example:
.select2-dropdown{
width: 180px;
}
In this implementation, the Select2 element is 90px wide by default but expands to 180px when the user opens it to type or make a selection.
Here is a quick demo for this post: https://codepen.io/anirugu/pen/YxMaqR
Thanks for reading!
Happy coding 