Thursday, June 26, 2014

Organizing Forms Using Fieldsets

I think some of the reluctancy of web developers to use fieldset elements to organize their forms stems from the fact that they don't look all that great by default. The legend element labels the fieldset element, which is rendered with an inset border around the whole thing. Another turn-off may be the fact that there's already a suite of styles that you can use to style your form elements — and using fieldset elements would just break the whole flow.

I've started to seriously think this is the wrong way to go about implementing styles in forms. There's no reason you can't style the fieldset and legend elements to match the look you're after. What you stand to gain from doing this is nice semantic markup, as seen here.

<form>
    <fieldset>
        <legend>General</legend>
        <label>First Name
            <input name="firstname"/>
        </label>
        <label>Last Name
            <input name="lastname"/>
        </label>
    </fieldset>
    <fieldset>
        <legend>Preferences</legend>
        <label>Send tons of spam
            <input name="spam" type="checkbox"/>
        </label>
    </fieldset>
</form>
This is a lot easier to follow if your scripts need to traverse the form DOM. Frankly, it's easier to write CSS styles for as well since the selectors can usually be much simpler.

No comments :

Post a Comment