Floating Labels Made Simple: A Clean HTML, CSS & JS Guide

61 0
Floating Labels Made Simple: A Clean HTML, CSS & JS Guide

Floating labels offer a sleek and user-friendly form experience. Instead of placing placeholder text inside the input field, the label hovers above once the user begins typing β€” making the form both functional and stylish.

🧱 Step 1: HTML Structure

This HTML layout sets up your form with labeled inputs. Each input triggers the floating effect on focus or blur.

<div class="center-space">
<div class="form-group">
<label for="full-name">Full Name</label>
<input type="text" class="input-group" onfocus="floatLabel(this, 'full-name')" onblur="floatLabelDown(this, 'full-name')">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="input-group" onfocus="floatLabel(this, 'email')" onblur="floatLabelDown(this, 'email')">
</div>
</div>

🎨 Step 2: CSS Styling

The following CSS styles control layout, spacing, and the floating behavior of labels when inputs are focused.

.center-space {
  padding: 30px;
  display: grid;
  justify-content: center;
  flex-wrap: wrap;
  gap: 20px;
}
.form-group label {
  display: block;
  position: absolute;
  background: #fff;
  top: 16px;
  left: 10px;
  padding: 2px;
  font-size: 15px;
  color: #a5a5a5;
  pointer-events: none;
  transition: 0.4s;
}
.form-group label.focused {
  top: -9px;
  font-size: 14px;
}
.form-group {
  text-align: left;
  position: relative;
  font-family: sans-serif;
}
input.input-group {
  padding: 10px;
  font-size: 15px;
  box-shadow: 5px 5px 5px #00000014;
  outline: none;
  border-radius: 4px;
  border: 1px solid #efefef;
  height: 50px;
}

🧠 Step 3: JavaScript Interaction

This JavaScript detects when the input is focused or blurred, and toggles the label’s position dynamically.

const floatLabel = (input, target) =&gt; {
  var inputValue = input.value;
  var targetLabel = document.querySelector("label[for='" + target + "']");
  targetLabel.classList.add("focused");
}
const floatLabelDown = (input, target) =&gt; {
  var inputValue = input.value;
  var targetLabel = document.querySelector("label[for='" + target + "']");
  if (inputValue == '') {
    targetLabel.classList.remove("focused");
  } else {
    targetLabel.classList.add("focused");
  }
}

πŸš€ Final Thoughts

Floating labels improve form clarity while keeping your UI minimal and elegant. This approach works smoothly across modern browsers and can be customized further for login screens, contact forms, or signup pages.

Link: Click Here

Devender Kumar

Devender Kumar

https://www.bydev24.com/

I'm Devender Kumar, a frontend developer with 8+ years in web development. I share practical code tips, clean UI designs, and tutorials to help developers build better sites.

0 comments

Leave a Reply

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