Floating labels Input fields

Explore our HTML category, where you’ll discover a plethora of helpful articles and tutorials suitable for beginners and experienced developers alike. Dive into various HTML elements and structures that can be employed in diverse projects, catering to their unique needs and specifications.
this CSS style creates a form input field with a floating label that smoothly transitions its position and size when the user starts typing or focuses on the input. This enhances the user experience by providing clear feedback and a clean visual presentation.
.field:has(input:not(:placeholder-shown)) label, .field:has(input:focus) label: This complex selector targets the label inside .field when the input is not in placeholder-shown state (meaning there is user input) or when the input is in focus. top: -1rem;: Moves the label up by 1rem when the conditions are met. font-size: 0.8rem;: Reduces the font size of the label for a subtle and compact appearance. pointer-events: initial;: Allows pointer events on the label, enabling interaction.
.field { position: relative; margin-bottom: 2rem; } .field input { border: 0; border-bottom: 2px solid #000; font-size: 15px; padding: 0; outline: none; } input:focus { border-bottom: 2px solid blueviolet; } input::placeholder { color: transparent; } label { position: absolute; top: 0; left: 0; transition: all 0.3s ease; pointer-events: none; } .field:has(input:not(:placeholder-shown)) label, .field:has(input:focus) label { top: -1rem; font-size: 0.8rem; pointer-events: initial; }
<form action=””> <div class=”field”> <label for=”email”>Email Address</label> <input type=”email” name=”email” id=”email” placeholder=”Enter Email”> </div> <div class=”field”> <label for=”password”>Enter Password</label> <input type=”password” name=”password” id=”password” placeholder=”Enter Password”> </div> <button>Submit</button> </form>