Back
Learn how to build an advanced input field with floating labels for a seamless user experience.
<div class="floating-container"> <input type="text" class="floating-input" placeholder=" " id="name" /> <label for="name" class="floating-label">Name</label> </div>
.floating-label
class provides the transformation effect that shifts the label above the input.
.floating-container { position: relative; margin-bottom: 20px; border-bottom: 2px solid #cccccc; } .floating-input { border: none; border-bottom: 1px solid transparent; width: 100%; outline: none; font-size: 16px; padding: 10px 0; } .floating-label { position: absolute; top: 10px; left: 0; font-size: 16px; color: #aaa; pointer-events: none; transition: all 0.2s ease; } .floating-label.floating { top: -20px; font-size: 12px; color: #2196F3; }
document.querySelectorAll('.floating-input').forEach(input => { input.addEventListener('focus', (e) => { e.target.parentNode.querySelector('.floating-label').classList.add('floating'); }); input.addEventListener('blur', (e) => { if (!e.target.value) { e.target.parentNode.querySelector('.floating-label').classList.remove('floating'); } }); });That's it! You've created an advanced floating label input field, providing a cleaner UI and an intuitive user experience.
<div class="floating-container"> <input type="text" class="floating-input" placeholder=" " id="name" /> <label for="name" class="floating-label">Name</label> </div> <script> document.querySelectorAll('.floating-input').forEach(input => { input.addEventListener('focus', (e) => { e.target.parentNode.querySelector('.floating-label').classList.add('floating'); }); input.addEventListener('blur', (e) => { if (!e.target.value) { e.target.parentNode.querySelector('.floating-label').classList.remove('floating'); } }); }); </script> <style> .floating-container { position: relative; margin-bottom: 20px; border-bottom: 2px solid #cccccc; } .floating-input { border: none; border-bottom: 1px solid transparent; width: 100%; outline: none; font-size: 16px; padding: 10px 0; } .floating-label { position: absolute; top: 10px; left: 0; font-size: 16px; color: #aaa; pointer-events: none; transition: all 0.2s ease; } .floating-label.floating { top: -20px; font-size: 12px; color: #2196F3; } </style>Thank you for reading this article.
Comments