Read more

How to make select2 use a Bootstrap 4 theme

Arne Hartherz
July 05, 2017Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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

Posted by Arne Hartherz to makandra dev (2017-07-05 18:26)