Bootstrap ยท Chapter 34 of 43

Bootstrap Floating Labels

Floating labels create a modern input style where the label starts inside the field as placeholder-like text, then animates upward above the input once the user types or the field has focus.

This pattern saves space and looks clean, and is built with the .form-floating wrapper class around a form control and its label.

Syntax
<div class="form-floating">
  <input class="form-control" id="name" placeholder="Name">
  <label for="name">Name</label>
</div>

Building a floating label

Wrap a .form-control (or select) and its <label> in a div with class .form-floating. The label must come after the input in the HTML for the CSS to work correctly.

Requirements

The input needs a placeholder attribute (even an empty one won't work well โ€” use a single space or the field's name) because floating labels rely on the :placeholder-shown CSS state.

Example 1 (html)
<div class="form-floating mb-3">
  <input type="email" class="form-control" id="floatEmail" placeholder="name@example.com">
  <label for="floatEmail">Email address</label>
</div>
Output
An input box where 'Email address' floats above the text once you click or type in the field

form-floating handles the animation that moves the label from inside the box to just above it.

Example 2 (html)
<div class="form-floating">
  <select class="form-select" id="floatSelect">
    <option selected>Choose...</option>
    <option value="1">One</option>
  </select>
  <label for="floatSelect">Select an option</label>
</div>
Output
A dropdown select with a floating label above it, like the text input version

Floating labels also work with <select> elements styled with form-select.

Key points

  • .form-floating wraps a form control and its label together.
  • The label element must come immediately after the input in the HTML.
  • The input needs a placeholder attribute for the effect to work.
  • Floating labels also work with select elements.
๐Ÿ’ก Note: Floating labels are a purely CSS-based effect and don't require any JavaScript.

๐Ÿ“ Quick Quiz

1. Which class enables the floating label effect?

2. In what order must the input and label appear in the HTML?

3. What attribute does the input need for floating labels to work?