In this small and quick CSS tutorial, we will learn how to style form input fields when user enters a valid value or invalid values.
Create a simple form with an email input field
1 2 3 4 5 | <form> <label for="email_id">Email ID</label> <input type="email" name="email" id="email_id"> <button type="submit">Submit Form</button> </form> |
CSS to style field for valid input values
1 2 3 4 | input[type="email"]:valid { color: green; box-shadow: 0 0 10px green; } |
CSS to style field for invalid input values
1 2 3 4 | input[type="email"]:invalid { color: red; box-shadow: 0 0 10px tomato; } |
We can further add :focus to show effect only when field is focused.
1 2 3 4 | input[type="email"]:valid:focus { color: green; box-shadow: 0 0 10px green; } |