How to line wrap text in legend elements, even in IE
Back in 2009 I wrote about a way of Line wrapping text in legend elements. It involved using CSS hacks or conditional comments to target Internet Explorer, which was the most problematic browser in this regard.
Well, it still is. All other browsers cooperate and let the text in legend elements line wrap by default. Older versions of Firefox don’t, but that’s fixed with this:
legend {
white-space:normal;
}
Internet Explorer, however, refuses. And that includes IE10, which forced me to look for another solution. Why? The old hack involves setting the legend
element’s width to 100%, and that has undesired side effects when no line wrapping is necessary (most of the containing fieldset
element’s top border is hidden). Previously you could use Conditional Comments or CSS hacks to target IE specifically. But there are No more conditional comments in IE10, and the only thing in terms of a CSS hack I have seen looks pretty messy.
I started trying out various things and eventually found that setting the legend
element to display:table
makes IE line wrap the text. Even better, it works all the way down to IE8 and does not seem to have any nasty side effects in other browsers. So here is the new fix:
legend {
display:table; /* Enable line-wrapping in IE8+ */
white-space:normal; /* Enable line-wrapping in old versions of some other browsers */
}
If you can live with legend
text not line wrapping in IE7 and older that’s all you need. You may even be able to remove the white-space
declaration if you’re not that concerned about old versions of Firefox (Safari and Opera have had automatic line wrapping of legends for a long time). For maximum backwards compatibility, leave the white-space
declaration in the rule and combine it with the hack in the older post I mentioned above (I keep that part in an ie.css
file loaded via conditional comments).
Some of you may be thinking “Well, legend text shouldn’t be that long anyway, so this should nearly never happen.” It’s true that legend text should not be too long, but that can be hard for us developers to control since it’s often our clients that enter the text. Plus, when you make a site responsive and it gets displayed in a viewport that’s only 320px wide (or even narrower) it doesn’t take a lot of text for this to become a problem.
Unless you apply this fix, of course.
- Previous post: Removing whitespace around text fields
- Next post: Using JavaScript to check if images are enabled