-
Book Overview & Buying
-
Table Of Contents
Designing Next Generation Web Projects with CSS3
By :
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:
:valid: It matches only fields that are in a valid state.
:invalid: It works in the opposite way, matching only fields with errors. This includes empty fields with the required attribute set to true.
:required: It matches only fields with the required flag, whether they're filled or not.
:optional: It works with all fields the without the required flag.
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).

Change the font size
Change margin width
Change background colour