DEV Community

FollowAndrew
FollowAndrew

Posted on

7 1

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

Image of Datadog

Measure and Advance Your DevSecOps Maturity

In this white paper, we lay out a DevSecOps maturity model based on our experience helping thousands of organizations advance their DevSecOps practices. Learn the key competencies and practices across four distinct levels of maturity.

Get The White Paper

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more