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) => {
var inputValue = input.value;
var targetLabel = document.querySelector("label[for='" + target + "']");
targetLabel.classList.add("focused");
}
const floatLabelDown = (input, target) => {
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

0 comments