Home / Fieldset and legend tags in HTML forms

Fieldset and legend tags in HTML forms

Last week I looked at the very useful <label> tag for HTML forms and this week look at the also very useful <fieldset> and <legend> tags which can help when breaking up a large form into several logical sections, or just to add a bit of style to a small form.

Example

I’ll start with the example and then show the code behind it. The <fieldset> tag draws a box around the set of fields and the optional <legend> tag inside it adds a title into the top part of the border. The input button could also be outside the fieldset and there can be more than one fieldset in a form.

Please login

The HTML

Here’s the HTML from the above example:

<form id="example_form">

    <fieldset>
   
        <legend>Please login</legend>
       
        <label for="example_email">Email Address</label>
        <input type="text" size="20" name="example_email" id="example_email" />
       
        <label for="example_password">Password</label>
        <input type="password" size="20" name="example_password" id="example_password" />
        
        <input type="submit" value="Login" />
       
    </fieldset>

</form>

You don’t neessarily have to use the <label> tags but given that I talked about them last week it made sense to use them again.

The CSS

The CSS below isn’t necessary for using a fieldset but it is what’s used to style the above example.

#example_form fieldset {
    width: 200px;
    padding: 3px 10px 10px 10px;
}
#example_form input {
    width: 190px;
}
#example_form input[type=submit] {
    margin-top: 3px;
    width: auto;
}