How do I create a CSS-only floating labels for form inputs?

Creating CSS-Only Floating Labels for Form Inputs

Floating labels are a popular design pattern for form inputs. They provide a clean, compact layout by displaying the placeholder text inside the input field, which then “floats” above the input field when the user starts typing. In this blog post, we’ll show you how to create a CSS-only solution for floating labels.

Step 1: Setting up the HTML structure

To create floating labels using only CSS, we’ll need a specific HTML structure. Let’s use a combination of <label> and <input> elements wrapped in a <div> container with a specific class.

<!-- html -->
<!DOCTYPE html>
    <link rel="stylesheet" href="styles.css">
        <div class="input-container">
            <input type="text" id="name" required>
            <label for="name">Name</label>
        <div class="input-container">
            <input type="email" id="email" required>
            <label for="email">Email</label>

Step 2: Basic styling for the form and input container

We’ll start by adding basic styles for the form and the input container. We’ll set a width for the form and style the input container to position the label and input elements properly.

/* CSS */
form {
width: 300px;
margin: 0 auto;

.input-container {
position: relative;
margin-bottom: 25px;

Step 3: Styling the input and label elements

Now, let’s style the input and label elements. We’ll remove the default input styles, set the font size and color for the labels, and position them using absolute positioning.

/* CSS */
input {
display: block;
width: 100%;
border: none;
border-bottom: 1px solid #ccc;
font-size: 16px;
padding: 5px 0;
outline: none;

label {
position: absolute;
left: 0;
top: 0;
font-size: 16px;
color: #999;
transition: 0.3s;

Step 4: Creating the floating effect

To create the floating effect, we’ll utilize the :placeholder-shown and :not pseudo-classes along with the general sibling combinator (~). This allows us to apply styles to the label when the input is not focused and has no value.

/* CSS */
input:not(:placeholder-shown) + label,
input:focus + label {
top: -20px;
font-size: 12px;
color: #009688;

That’s it! With these simple CSS rules, you’ve created floating labels for your form inputs without using any JavaScript. The label will now float above the input field when the user starts typing or focuses on the input field.

Got question?

Submit it here

© All rights reserved.