Fieldset and Legend

One problem with fieldset and legend is that different browsers style them differently. One particular issue is where we want to apply a background colour to our fieldset. Because the legend usually sticks out of the top of the fieldset the way that a background colour is applied to the fieldset is inconsistent. Some browsers will apply the background only inside of the fieldset border while others extend the background colour out of the top of the fieldset so as to include all of the legend.

Provided that we do not want to display the fieldset border we can apply a couple of simple styles to the fieldset and legend so that the background of the fieldset always includes the entire legend. We do this by applying position:relative to the fieldset and position:absolute to the legend. This takes the legend out of the regular flow of the page. We now apply sufficient padding-top to the fieldset to make room for the legend to be displayed above the rest of the fieldset content and apply top:0 to the legend so that it displays at the top of the fieldset (as some browsers treat the top padding differently than normal for a fieldset and will position the legend below the padding over the top of part of the form if we do not reset top to zero).

Here we look at a fieldset with a grey background and the legend styled to look like a form heading. One input field is included to show how it always appears below the legend when we use this CSS.

fieldset {position:relative;background-color:#ccc;border:none;padding-top:3em;}
fieldset legend {position:absolute; top:0;display:block;font-size:2em; line-height:1.1;border-bottom: 1px solid #666;}

Here is how the fieldset and legend look when styled this way:

Form Heading

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate