Change default font of Select2

2020-03-30 04:32发布

问题:

I am using the Select2 plugin to add the search feature to my dropdowns. However, I want the font style of these drop downs to be set to the same font as my other fields: font-family: Arial, Helvetica, sans-serif;

My 'Select' HTML:

<label>Department</label>
<select class='js-example-basic-single' name="department" id="department" required>
  <option value="Dep 1">Dep 1 </option>
  <option value="Dep 2">Dep 2 </option> etc.....
</select>

My JavaScript:

$(document).ready(function() {
  $(".js-example-basic-single").select2({
    placeholder: "Please Select an option",
    allowClear: true
  });
});

I'm sure there is an easy answer to this, but couldn't seem to find one.

回答1:

select2js provide different classes and id selectors for different sections of the Select HTML tag.

For specific changing the Select OPTION font-size, we can use the following class selector to change the same acc to our requirement.

.select2-results__options{
        font-size:14px !important;
 }


回答2:

the only css class I needed to change (for single-selects) was:

.select2-selection__rendered {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
}


回答3:

In my case, I wanted to change the background color of the Select2. So what I did is found the select2 class name that controls that feature. I added my desired color to the css of the same class name affecting that feature and made sure that updated css loaded after the select2 stylesheets. I did some minor tweeks the same way to the jquery themes.



回答4:

I stumbled across this feature this morning and it worked! It uses containerCssClass.

    <style type="text/css">
        .myFont {
            font-size:x-small;
        }
    </style>
    <select id="m"><option>one</option><option>two</option></select>
    <select id="n"><option>three</option><option>four</option></select>
    <script type="text/javascript">
        $("#m").select2({ containerCssClass: "myFont" });
        $("#n").select2();
    </script>

The first box had tiny font, and the second one had regular font. He also added the dropdownCssClass option.



回答5:

<select class='js-example-basic-single' name="department" id="department" style="font-family: Arial, Helvetica, sans-serif;" required>
    <option value="Dep 1">Dep 1 </option>
    <option value="Dep 2">Dep 2 </option> etc.....
    </select>