How to add shake animation on input:invalid

dev_steve

Stephen

Posted on September 27, 2022

How to add shake animation on input:invalid

In this short article we'll create a simple HTML with an input tag in a form tag and animate the input when user input is not valid.
This might seem a bit difficult and you may think you need Javascript to complete this task,but with only HTML and CSS(keyframes) we'll get this done.

Let's write some code

Adding our HTML

<!DOCTYPE html>
<head>
    <meta charset="UTF-8" />
</head>
  <body>
     <form action="">
        <input type="text" minlength="5" />
      </form>
  </body>

</html>
Enter fullscreen mode Exit fullscreen mode

Using the :invalid pseudo selector

In our css we style the input with the :invalid pseudo selector

<style>
input:invalid{
animation:shake .3s
}
</style>
Enter fullscreen mode Exit fullscreen mode

Adding shake animation with keyframes

Animations in CSS are mostly done with keyframes and so will our shake animation

<style>
.....
@keyframes shake{
25%{transform:translate(4px)}
50%{transform:translate(-4px)}
75%{transform:translate(4px)
}}
</style>
Enter fullscreen mode Exit fullscreen mode

Final Results

We set the minimum length of our input to 5, this means the input is invalid if the user enters less than 5 characters.
And the input box shakes when the user input is less than 5 , thus the form is invalid

💖 💪 🙅 🚩
dev_steve
Stephen

Posted on September 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related