Recently I was creating a small Blazor project where I wanted to create a floating label, and realised that it could be done with simple CSS.
To start let’s create an input with a label:
<div class="float" style="position: relative;">
<input type="email" class="input" placeholder="[email protected]" id="input" />
<label for="input">Email Address</label>
</div>
The div
has a style to set the position
to relative
. That way everything that goes on inside will be relative to the parent element.
Note: It’s important that you have a placeholder (even though it won’t show, as that is used for toggling the label
.
Let’s add some basic styling to the input
, along with height
and padding
to allow space for the label to fit inside:
.input {
font-size: 1rem;
border: 1px solid #ced4da;
border-radius: .375rem;
line-height: 1.25;
font-weight: 400;
padding: 1rem .75rem;
}
Now let’s fix the label
to sit inside the input
box by default:
label {
position: absolute;
top: 0;
left: 0;
padding: 1rem .75rem;
line-height: 1.25;
pointer-events: none;
color: rgb(94, 94, 94);
transition: all 0.15s ease 0s;
}
.float > .input::placeholder {
color: transparent;
}
We’ve set it’s position
to absolute
(which is relative
to the parent div
). We also set pointer-events
to none
to ensure when clicking the input
the label
doesn’t take the focus thereby removing the ability to actually put in a value.
Finally, we only need one last CSS declaration to do the actual transition to float:
.float > .input:focus ~ label,
.float > .input:not(:placeholder-shown) ~ label {
color: #d22f25;
transform: scale(.85) translateY(-1rem) translateX(-.5rem);
}
Here we are setting both when the input
has focus
, and when a value has been entered into the input
but it’s no longer in focus. We change the colour to red, scale down the font-size
and move it up to the top of the box. Since we added a transition
to the label
any change it makes automatically gets it. So the move will work smoothly.
You will want to play around with the padding
, colours
and height
etc. so that it fits and matches your site.
Here is an example: