How to make select2 use a Bootstrap 4 theme

Posted . Visible to the public.

select2 Show archive.org snapshot is a great jQuery library to make (large) <select> fields more usable.

For Bootstrap 3 there is select2-bootstrap-theme Show archive.org snapshot .
It won't work for Bootstrap 4, but rchavik's fork Show archive.org snapshot does (at least with Bootstrap 4 Alpha 6, current version at time of writing this).

It is based on a solution by angel-vladov Show archive.org snapshot and adds a few fixes.

Use it by adding it to your project and requiring Sass files as follows.

// Include your custom Bootstrap variables instead, if you have some.
@import ~bootstrap/scss/bootstrap/variables
@import ~bootstrap/scss/bootstrap/mixins
@import ~font-awesome/scss/font-awesome

@import ~select2/src/scss/core

@import ~select2-bootstrap-theme/src/select2-bootstrap4.vars
@import ~select2-bootstrap-theme/src/select2-bootstrap
@import ~select2-bootstrap-theme/src/select2-bootstrap4.after

Note I use the ~ to reference libraries in my Webpack build pipeline. Depending on your setup, you may need something else, or nothing at all.

Then select2ify your controls. Note that you need to specify a theme or the above won't work:

$element.select2({ theme: 'bootstrap' })

I recommend adding the following Sass to make empty options the same height as non-empty options:

$option-line-height: $line-height-base * $font-size-base + 2 * $input-padding-y

.select2-container--bootstrap
  .select2-results__option
    &:empty
      min-height: $option-line-height

It's so pretty!

Example screenshot

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2017-07-05 16:26)