9.18. Field Labels

The label tag (<label>) is used to define text labels for fields. This tag has the following format:

<label for="id_of_related_tag">text_label</label>

For example, the following code defines a label for a text box:

<p><label for="FirstName">First Name: </label>
<input type="text" name="FirstName" id="FirstName" value=""
size="30" maxlength="40"></p>

The label field's for attribute should match the id of the field for which it is intended. The main purpose of the label tag is accessibility—most users will be able to ascertain the purpose of fields in your forms by sight. However, if the user agent does not have a visual component, or if the user is visually impaired, the visual layout of the form cannot be relied on to match labels and fields. Note that if the user agent supports it, the user can also click on the field label to select the appropriate field.

The <label> tag's for attribute ensures that the user agent can adequately match labels with fields for the user, if necessary.

Notice the use of both the id and name attributes in the text input field tag. HTML requires a field to have a name tag for its data to be submitted. However, the label tag requires an id value in its matching input field.

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.