Floating label for input in CSS
Have you seen these kind of floating labels in forms? I used to think you need some JavaScript to make these. But nope, you can do it in pure CSS :)
But before we start, why do we even need floating labels? If you're considering the pros and cons, you can check out this article by Brad Frost.
Now let's see how it's done.
It's not a placeholder
It looks like the input placeholder itself moves up to become a label. That's the first trick! The text you see there is not actually a placeholder. It's a label that's positioned absolutely on top of the input.
So first add a label
element after input
. Then wrap them both in a div
and position the label
absolutely to make it look like a placeholder.
Move the label when input is focused
1. Firstly since the label is positioned on top of the input, clicking on the label will not "pass" the click to the input behind it. (It took me a while to figure out why the input is not responding on click)
So you need to add the rule pointer-events: none
to the label
2. When the input
is focused, you can select the label
(using the sibling combinator +
) and translate
the label
to the top.
And while translating it, you'll want it to move smoothly, to add this transition too:
It's almost working, but...
This works already! You click on the input, it's focuses and so the "placeholder" moves up. But what if you type something and focus out of the input? Oops! The placeholder appears on top of the text. That's not desired.
Also, this happens when the input is auto-filled by the browser. To fix these two cases, we need to add two more selectors like so.
This fixes it and we have a nice floating label! Did you get to work?
If not, here's the working demo. Hope you learnt something new this time :)
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.