Two Ways to Attach Labels

The HTML standard provides two different ways that you can attach a label to a form field.

The first way and in my opinion the more semantically correct way is to give the form field an id and reference that id from the for attribute of the label.

<label for='email'>Email Address: </label><input id="email" name="email" ...

The second way is to nest the form field inside the label.

<label>Email Address: <input name="email" ...></label>

This second way is shorter because it does away with the need for two attributes (except in some older browsers that didn't support the standard properly and required that you both specify the id and for attributes and nest the form field). It can only be used though when the label text is directly adjacent to the form field it applies to so you would have to use the first way if the content is arranged some other way (eg. with the form using a table with the labels in the first row and the fields they refer to below them in a second row).

To me this second arrangement makes it look like the form field itself is a part of the label and that you are allowing your visitors to enter a part of the label with the label not actually referencing anything - unless you were to code it as:

<label id="myfld"><input name="myfldlabel" ...></label><input id="myfld" name="myfld" ...

Now of course with the way that the relationship is defined by the standards this version where your visitor can supply their own label in a second input field would be invalid even though it is semantically meaningful simply because the two ways of specifying what is being labelled is now in conflict.

So while the second way of attaching labels is shorter it cannot be used in every instance and it prevents you from being able to define dynamic labels (as well as being less semantic in my opinion). Both ways though are valid according to the standards and so it is really your choice as to which of the two ways that you will use to attach labels to all the fields in your forms.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow