Line wrapping text in legend elements

In some cases you should Use the fieldset and legend elements to group HTML form controls. One problem that may lead to though is when the legend text is too long to fit the width of its containing fieldset element.

It could be because the legend text simply is longer than it really should be (legend texts should be as brief as possible) or because its parent fieldset isn’t wide enough (it may be displayed in a narrow column, for instance). The end result is the same—most browsers do not line wrap legend text but keep it all on one line. This in turn can lead to legend text overlapping other parts of the page and becoming hard to read, especially if text size is increased a bit.

Recently I had a reason to try to find a workaround, and I managed to come up with something that seems to work in most browsers. Not all of them, and not in all versions, but it does work for the majority of users.

Opera and Safari (not sure from which versions or they always have) line wrap legend text by default. No extra CSS necessary. A little white-space:normal fixes Firefox 3.

IE 8 doesn’t care about white-space:normal, but float:left works. That doesn’t work for IE 6 or 7, however. Luckily, wrapping the contents of the legend element in a span element and floating that does work.

You can’t just float the legend and span elements in your main stylesheet though, since that will have unwanted effects in several browsers. So you need to make sure only IE sees that rule.

One more problem is that in IE 8, if the legend text does not wrap, the floated legend causes problems, so you need to clear the float somehow. The only solution to that problem I’ve been able to find is to wrap the rest of the `fieldset` content in a `div` element. Yeah, it’s messy.

Summing it all up, the CSS that will make text in a legend element wrap in most browsers is this:

/* For all browsers */
legend {white-space:normal;}
/* For Internet Explorer only - put in a separate file and load it with conditional comments or find a CSS hack that works with IE 8 */
legend span {float:left;}
.fieldset-content {clear:both;}

My personal preference when dealing with CSS that is specifically for IE is to use Conditional Comments. You may prefer CSS hacks—the choice is yours.

I made a quick demo page so you can check the result in your browser.

Anyone happen to know of a better way of line wrapping text in legend elements?

Posted on May 18, 2009 in CSS