bootstrap-4jquery-select2

Select2 with Bootstrap theme not honoring input group class


I'm trying to use the select2 with an input group, but the button is always on the next line after the select2 control. If you remove the select2 class it works as expected. Why does the select2 bootstrap not honor the standard bootstrap input group classes if it's based on the bootstrap theme? What am I missing to ensure they are both on the same line and displayed as a group?

Without select2 class (and how I would like it to look) enter image description here

With Select2

enter image description here

With Select2 and adding style="width:75%" (off at bottom) enter image description here

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" />
    <link rel="stylesheet" href="https://select2.github.io/select2-bootstrap-theme/css/select2-bootstrap.css" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.full.js"></script>
</head>
<body class="container">
    <p></p>
    <div class="input-group">
        <select class="form-control select2" placeholder="Search"></select>
        <div class="input-group-append">
            <button class="btn btn-success" type="submit">Go</button>
        </div>
    </div>
</body>
</html>

<script>
    $(".select2").select2({
        theme: "bootstrap",
        placeholder: "Search"
} );
</script>

Solution

  • Yea the default bootstrap style from Select2 doesn't work that well with bootstrap. You need to write some custom styles to get what you want:

    .input-group > .select2-container--bootstrap {
        width: auto;
        flex: 1 1 auto;
    }
    
    .input-group > .select2-container--bootstrap .select2-selection--single {
        height: 100%;
        line-height: inherit;
        padding: 0.5rem 1rem;
    }
    

    Select2 has fixed width and height for the fakery search box. You have to reset them. You also need to turn on the ability of grow and shrink for the fakery search box, with flex: 1 1 auto;.

    enter image description here

    demo: https://jsfiddle.net/davidliang2008/o0tLw56f/15/