Search code examples
cssbootstrap-4labelbootstrap-selectbootstrap-selectpicker

How to get :focus & :valid value like form-control from bootstrap-select?


I am trying to add a float label on bootstrap selectpicker with only css. So in my code I want to float the label with bootstrap-select:focus. But the problem is this line doesn't work in the css. But if I use bootstrap-select:active, when holding mouse this seems to work.

I tried the floating label with normal selectbox applying form-control and in the normal selectbox everything works fine, but I want my selectbox to be more functional & good looking, so I am trying to use selectpicker. In form-control I used :focus & :valid to get the selectebox state and applied the floating label. This is the example with form-control

This is the code with .bootstrap-select:active that works with mouse click.

.bootstrap-select:active + .form-control-placeholder {
    color: #da3338 !important;
    transform: translate(0, -1.2em);
    font-size: 70%;
    transition: 0.2s ease-in-out;
}

This is the example with selectpicker

The main point is that I want the label to float when the selectbox is focused, also when a valid option is selected from the drop down menu. I want to do this with pure css, but if I need js/jQuery I won't mind, so any help will be appreciated.


Solution

  • Well after spending days in google I have come to a solution!

    css classes:

    .float {
        color: #da3338 !important;
        transform: translate(0, -1.1em);
        font-size: 75%;
        transition: 0.2s ease-in-out;
    }
    
    .changefloat {
        transform: translate(0, -1.1em);
        font-size: 75%;
    }
    

    jquery:

    function float (){
        $(this).parents(".form-group").children("label").addClass("float");
    }
    function unfloat (){
        $(this).parents(".form-group").children("label").removeClass("float");
    }
    function changefloat (){
        $(this).parents(".form-group").children("label").addClass("changefloat");
    }
    
    $(".selectpicker").on("show.bs.select", float);
    $(".selectpicker").on("hide.bs.select", unfloat);
    $(".selectpicker").on("changed.bs.select", changefloat);
    

    Working example