big_smile big_smile - 4 months ago 6
HTML Question

HTML Correct way to wrap labels and fields

What's the correct way to wrap fieldset and labels in HTML?

E.g.

<label> First name </label>
<input type="text" name="firstname">

<label> Nick Name </label>
<input type="text" name="Nickname">

<label> Surname </label>
<input type="text" name="Surname">

<label> Favourite Color </label>
<input type="text" name="favourite-color">

<label> Favourite TV Show </label>
<input type="text" name="favourite-tv-show">

<label> Favourite Food </label>
<input type="text" name="favourite-food">


I want to wrap each label and input in a HTML tag, so they are easier to arrange into a grid.

e.g.

<div>
<label> First name </label>
<input type="text" name="firstname">
</div>

<div>
<label> Nick Name </label>
<input type="text" name="Nickname">
</div>


Is fieldset the correct tag? I wasn't sure if you were supposed to use that for individual label and input pairs or for groups of them (e.g. all the Name inputs would be in a fieldset tag and all the favourites would be in another fieldset tag).

I know I can use a DIV (as in my second example), but I am not sure if that is the best tag.

Answer

There are several correct ways. You can wrap them in a div, or in a span, or inside cells of a table row. Other approaches are possible, too, but less natural. A fieldset element is for a group of controls and associated labels. A group with a single control is formally correct, but rather pointless. Neither div nor span has any meaning assigned to it, apart from constituting a block level or inline element, respectively. But since you probably want each control to start on a new line, div makes things simpler, as it has such rendering by default. A table element constitutes a grid of elements and is therefore a natural choice, because a collection of controls and associated labels logically forms a grid.

In any case, note that label elements as used in the example are rather pointless and provide no functional advantages. They should have for attributes that associate each of them with its control, by its id attribute.