Preloader

Floating Labels

bootstrap

In most older web designs, the labels position themselves above or to the left of the input box. Bootstrap‘s Floating Labels position the label within the input box. As you begin to type away, it “floats” to the top corner of the input box.

It‘s a slick, modern design that is space efficient and maintains nice, tidy forms.

1. How it Works (The Magic)

Bootstrap relies on a states technique with :placeholder-shown and some smart CSS transitions.

  • When Empty: The label appears as if it is placeholder text in the box.
  • When Focused/Typed: The label decreases in size then floats to the top-left until the user knows which field they are filling out.

2. The Basic Structure

To make this work, you need three specific things in your HTML:

  1. A Wrapper: you have to wrap the <input> and the <label> inside a <div class=“form-floating”>.
  2. Order Matters: The <input> must come before the <label>.
  3. The Placeholder: The <input> will require the placeholder attribute (even if it is empty, i.e placeholder=” ”) this is required for bootstrap to determine whether the box is being “used” or not.

Example Code:

HTML

<div class="form-floating mb-3">
  <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
  <label for="floatingInput">Email address</label>
</div>

3. Key Rules to Remember

  • Form Controls only: (will only work with .form-control the input-controls and.form-select the list-items)
  • Input Types: It works with text, email, password, and even textareas.
  • Height: If you use a <textarea>, the floating label will stay at the top while the user types multiple lines.

4. Pros and Cons

ProsCons
Saves Space: No need for extra margins above inputs.Browser Support: Requires modern browsers to work perfectly.
Better UX: The label never disappears, unlike standard placeholders.Strict HTML: If you forget the placeholder attribute, it breaks.
Modern Look: Feels like a high-end mobile app.Select Scaling: Can look a bit cramped in very small dropdowns.

5. Using it with Selects (Dropdowns)

With a < select> menu, no matter which option you pick, the label should always be floated up for a dropdown (even if it was simply just the “Choose…” option).

HTML

<div class="form-floating">
  <select class="form-select" id="floatingSelect">
    <option selected>Open this menu</option>
    <option value="1">One</option>
  </select>
  <label for="floatingSelect">Works with selects</label>
</div>

Check out our resources!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *