Bulletproof superscripts and subscripts
By Ruthie BenDor on May 25, 2010
Ever need to consistently style superscripts and subscripts, but find that your line heights are getting messed up? My solution—tested in IE6 and above—after the jump.
I just wrapped up a project which involved marking up legal documents in a web-friendly manner. Part of the process involved wrapping each footnote reference in a <sup> tag. I started simple:
sup { vertical-align: super; }
sub { vertical-align: sub; }
But upon previewing my design in a variety of browsers, I noticed my carefully crafted line heights were getting all messed up, breaking the vertical rhythm of the page and in general lookin’ gnarly.
The solution, it seems, is to explicitly position <sup> and <sub> relative to the surrounding text. Once you’ve done this, it’s fairly straightforward to apply top and bottom positioning to each element as necessary. Two gotchas, though:
- If you’re adjusting the font size downward, trying to figure out what the line height should be is pretty tricky. My suggestion, as reflected in the code below, is to zero it out. This doesn’t seem to mess anything up in any of the browsers I tested, and in fact resulted in more consistent vertical positioning.
- Most user agent stylesheets will by default apply some version of the CSS above to these elements. Make sure to overwrite those default styles by applying a
vertical-align: baseline;rule before adjustingtop:andbottom:properties. If you’re using some version of Eric Meyer’s reset stylesheet, this rule may already be applied, so no need to repeat yourself.
Full example code, commented to explain what each line is doing.
I’ve tested this in IE6 and above, as well as Mac/Firefox 3.5, Mac/Safari 4, and Mac/Chrome 5. If you have access to other browsers and platforms, please try this out and let me know if something breaks. Thanks!
Comments
jason said on Jan 2nd, 2012:
This is great, I met one issue before because of the script. Now it has been solved after seeing your scripts(statinternet). Thanks for the sharing!