13

Nov

CSS Positioning the Legend Tag

So lately I’ve been working on validating code. I don’t often have to rely on a validator but I didn’t write this markup and some of it was very hastily written. That’s not important but it is how I came to find some strange cross-browser bugs and I’d like to share one I found during the validation process.

Now, the rule for the legend element is that it can only be nested inside a fieldset and it can only be the first child. This seems a bit obvious but I was unaware it was so strict. But the way in which the browsers treat CSS applied to this element is the interesting part. If you’re in Safari (3.1), Opera (9.62) or Internet Explorer (IE7) then you’ll find that the legend element acts more like a block element that has a default position in the upper left of the fieldset. Whereas, in Firefox (3.0), the legend element is going to stick in the upper left-hand corner of that fieldset pretty much regardless of the CSS. Positioning, floating and text-align all don’t work on the legend element in Firefox but have the expected behavior in other browsers.

A key exception to this is how IE treats legend elements that are floated. IE, it seems, will keep the legend on the top border of the fieldset if you float it. Whereas, in Safari and Opera you’ll find that the legend element will float inside of the box layout of the fieldset.

So, the takeaway here is that you really shouldn’t try to position the legend element any other place other than the upper left-hand corner, otherwise your layout will look quite different across the various browsers.