Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I style the backgrounds of Bootstrap's new form-floating input labels?

I am using Bootstrap 5.3, and trying to use the new "floating labels". I would like my inputs to have additional styling, such as background colors. When I add a subtle green background color at first, it looks fine when there is no value set, but as soon as you focus in or add text, you get this:

enter image description here

If I add a background color to the label, it doesn't style the white part there, it styles some region surrounding it:

enter image description here

Does this have something to do with :before/:after? Will someone please shed some light on this black magic? I am using Brave, and it needs to work in Brave.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>


<div class="w-25 p-3">
    <div class="form-floating">
        <input class="form-control" type="text" placeholder=" " id="myElement" style="background-color: var(--bs-success-bg-subtle); color: var(--bs-success-text-emphasis); border-color: var(--bs-success-border-subtle);">
        <label class="form-label" for="myElement" style="color: var(--bs-success-text-emphasis); background-color: red;">Name</label>
    </div>
</div>
like image 784
Matthew Beck Avatar asked Sep 05 '25 00:09

Matthew Beck


2 Answers

You may simply remove the background when the label is in focus

.form-floating > label::after {
    background-color: transparent !important;
}
like image 100
yansusanto Avatar answered Sep 07 '25 19:09

yansusanto


The background has the same color as the input. So it needs to be reset after the input gets his :focus.

If you want to keep the smaller label red; add another background on the label:after when input:focus.

The issue is that you don't want to background on the label if there is some content. Currently you can use the placeholder-show property, which is quite well supported as shown on Can I Use?.

.form-floating > input:not(:focus):placeholder-shown + label {
     background: red;
}

.form-floating > input + label:after {
    background: red !important;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>


<div class="w-25 p-3">
    <div class="form-floating">
        <input class="form-control" type="text" placeholder=" " id="myElement" style="background-color: var(--bs-success-bg-subtle); color: var(--bs-success-text-emphasis); border-color: var(--bs-success-border-subtle);">
        <label class="form-label" for="myElement" style="color: var(--bs-success-text-emphasis);">Name</label>
    </div>
</div>

enter image description here

like image 37
0stone0 Avatar answered Sep 07 '25 19:09

0stone0