DEV Community

FollowAndrew
FollowAndrew

Posted on

Animated Floating Input Labels CSS ONLY!

Lots of forms are using placeholder text and not hiding the label (or not using it altogether) and it's often difficult to remember what the form element was when you click in. To create a better user experience for this, we can animate the input labels above the form element when they are clicked. Best yet, this is a pure CSS solution!

Subscribe To The Channel!


Watch the Video Tutorial on YouTube for a visual explanation!

There are sevearl tricks to get this to work:

  • Position the label over the input label
  • Make the placeholder text invisible
  • Use fancy CSS pseudo selectors to animate & transform the labels on click
  • Use the even fancier CSS selector of ":not(:placeholder-shown)" -- Bet you didn't know about that one!!! to make sure the labels stay animated when tabbing away from the input.

Here's the most magical selector that does the trick.

.form-control:focus + .form-label,
.form-control:not(:flaceholder-shown) + .form-label{
    transform:translateY(-2.5em) scale(.8);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
bherrero profile image
Borja Herrero • Edited

Hi Andrew, nice article.
There's a typo in your code though, you misspelt placeholder-shown, using flaceholder-shown instead.