HTML and CSS Reference
In-Depth Information
The label Element
As you may guess from its name, the
label
element serves to give a label to each widget in
your form. More than anything, the
label
element serves important usability and accessibility
functions. In most user agents, clicking on a field's label will bring the keyboard focus to that
field.
label
elements also help assistive technology like screen readers understand the rela-
tionship between a textual label and a form field. The
label
element can be used one of two
ways in (X)HTML. It can be wrapped around the field it is associated with, like so:
<label>Street <input id="street" name="street" type="text" value="Street" /></label>
In this method, the relationship is implicit; because the
input
field with the
id
attribute
value
street
is nested within the
label
element, the label is related to that field. The relation-
ship can also be defined explicitly:
<label for="street">Street</label>
<input id="street" name="street" type="text" value="Street" />
Here, the
input
element is not nested, so the relationship is defined explicitly by using the
label
element's
for
attribute—it is set to the
id
value of the related form element. When
defining relationship explicitly, the
label
element doesn't need to be near the form element to
which it relates in the (X)HTML source. Once in a while, this proves advantageous, but most of
the time, it really doesn't matter which way you choose to use the
label
element.
Our Example Form
For the rest of the examples in this chapter, we'll be using this example form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
➥
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Example form</title>
<link rel="stylesheet" href="reset-min.css" type="text/css" media="screen" />
<link rel="stylesheet" href="basic.css" type="text/css" media="screen" />
<link rel="stylesheet" href="intermediate.css" type="text/css" media="screen" />
</head>
<body>
<form id="payment_form" action="/path/to/action" method="post">
<fieldset id="name">
<legend>Name</legend>
<label>Title
<select id="title1" name="title1">
<option selected="selected">Mr.</option>
<option>Mrs.</option>
<option>Ms.</option>
</select>