ChApteR 4 ■ CSS3 tRAnSItIonS foR UI elementS
The only slightly unusual aspect of this stylesheet is the third declaration, which underlines the first letter of
each form label to show the appropriate accesskey for the associated field. To display whether the information
entered into the input is right or wrong, you need to add the code in Listing 4-19. (Note the first CSS declaration,
which turns off the current default Firefox UA styles for valid and invalid inputs).
Listing 4-19. CSS for a Typical Accessible Form
input:valid, input:invalid {box-shadow: none; }
input:valid { border: 2px solid green; }
input:invalid { border: 2px solid yellow; }
While you could certainly animate what you have so far, there are a few drawbacks to the form as it is
currently presented: the browser defaults to showing the inputs as invalid when the user first sees the page,
and there’s no indication of exactly what the user entered incorrectly.
You can’t use pseudo-classes to generate error messages after the inputs because they are replaced
elements, but you can place the error messages in the title attribute of spans after the inputs. Some examples
are shown in Listing 4-20.
Listing 4-20. Span Elements Added As Validation Error Messages After HTML5 Form Inputs
Because each span only contains information in its title attribute and has no visible content, older
browsers that don’t fully support CSS3 are disabled from showing any confusing messages to the user. Remove
Listing 4-20 from your code and replace it with Listing 4-21.
Listing 4-21. Styling and Displaying Validation Errors
input + span:after { content: attr(title); color: red; margin-left: 0.6rem; opacity: 0; }
input:invalid + span:after { opacity: 1; }
There’s an immediate problem: the browser continues to show the inputs as wrong by making the
span title attribute visible the moment the page loads. The reason?
■ Tip An input with a required attribute is evaluated by its pattern or input type before the user focuses or
enters any information into the field.
By removing the required attribute from the inputs and adding a transition to the error messages, as in
Listing 4-22, you achieve the effect you are after. Note that I’ve added a delay to the transition: without this, the
error message would show immediately on entering the first character in a field. You want a reasonable amount
of time to pass before you start telling the user that their information is wrong.
Listing 4-22. Displaying a Form Validation Error Message After a Delay
input + span:after { content: attr(title); color: red; margin-left: 0.6rem; opacity: 0;
transition-property: opacity;transition-duration: 2s; transition-delay: 2s;}