Introduction
In this lab, we will explore CSS animations and pseudo-classes to create an input validation effect. Specifically, we will create a shake animation on invalid input using keyframes and the :invalid pseudo-class. This lab will help you improve your CSS skills and learn how to add dynamic and engaging effects to your web pages.
Shake on Invalid Input
index.html and style.css have already been provided in the VM.
To create a shake animation when there is invalid input, follow these steps:
- Use the
patternattribute to define a regular expression that specifies the allowed input. For example, use[A-Za-z]*to allow only letters. - Define a shake animation using
@keyframes. Set themargin-leftproperty to move the input left and right. - Use the
:invalidpseudo-class to apply the shake animation to the input. - Optionally, add a red box-shadow to the input to indicate the error.
Here's an example code snippet:
<input type="text" placeholder="Letters only" pattern="[A-Za-z]*" />
@keyframes shake {
0% {
margin-left: 0rem;
}
25% {
margin-left: 0.5rem;
}
75% {
margin-left: -0.5rem;
}
100% {
margin-left: 0rem;
}
}
input:invalid {
animation: shake 0.2s ease-in-out 0s 2;
box-shadow: 0 0 0.6rem #ff0000;
}
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the Shake on Invalid Input lab. You can practice more labs in LabEx to improve your skills.