Let's look at an easy trick to automatically display an asterisk (*) near the labels of required fields. The HTML5 form validation model introduces some new and very interesting pseudo-selectors:
In our case, we need to match all the labels that follow a field that has the required
attribute. Now the HTML5 structure we implemented earlier comes in handy because we can take advantage of the +
selector to accomplish this.
input:required + .label:after, input:required + * + .label:after{ content: '*'; }
We added a small variation (input:required + * + .label:after
) in order to intercept the structure of the radio buttons as well.
Let's analyze the sentence a bit before moving on. We used the
:after
pseudo-selector to get access to the location just after the element with a label
class. Then, with the content
property, we injected the asterisk within that location.
If we reload the page we can verify that, now, all the labels that belong to fields with a required
flag end with an asterisk. Someone may point out that screen readers do not recognize this technique. To find a way around this, we can take advantage of the
aria-required
property, part of the WAI-ARIA specification (http://www.w3.org/TR/WCAG20-TECHS/ARIA2).