Select2 is unresponsive, width is larger than container
I have a problem with select2 dropdown width in my ASP.NET page. When I try to view a page with a Chrome emulator screen, select2 is larger than the containing div and on the right it comes out of the screen. I saw with checking the code that it automatically adds a style attribute style="width: 498px;"
on an element <span class="select2 select2-container select2-container--bootstrap select2-container--below">
that I have not set anywhere. The only operation I did was 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 do I remove this style = "width" option?
source to share
Select2 adds a class .select2
. You can override what script uses css. Here I install select2 for 100% width
using !important
. If I hadn't, then select2 would be 24px wide.
You can further customize other classes that it select2
generates using some principle.
$(document).ready(function(){
$("#mySelect").select2();
});
.select2 {
width:100%!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
<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>
source to share
<span>
with the class .select2
is created by the Select2 plugin immediately after creating a new select2 in the given one <select>
.
To make this element span.select2
responsive, we may have some possibilities, such as:
- Use a% width (either on the original before creating the select2 element, or in the select2 width option ).
- Override via CSS (e.g. when using queries
@media()
). Please note that this may affect the functionality or display of the plugin.
For the second, we can use the adjacent sibling combinator ( +
) with the !important
width-wise style of our select2 <span>
, since usually the select2 range is created and inserted immediately after ours <select>
.
See example below:
@media (max-width: 400px) {
select.my-x-select + span.select2 {
width: 200px !important;
}
}
Note: select
and span
element selectors are not needed @media
as an example of use.
source to share