Font-size and Line-height for <pre>, <code>, and Other Monospaced Fonts

While attempting to create a consistent cross-browser font baseline, I ran into the following strange behaviour in certain browsers (not IE for once!). Any monospaced font was rendered smaller than the surrounding text, even when specifically set to display at 1em. I found this to be true in both Firefox and Chrome. After a bit of searching, I found that these browsers also contain a strange bug, although in this case it almost becomes a feature. If the font-family is set to monospace twice, suddenly the font displays at the proper size:

pre, code, kbd, samp, tt, textarea{
	font-family: monospace, monospace;
}

However, in Chrome, this threw off the line height, which ruined the vertical rhythm I was working to create. After some trial and error, I discovered that setting the vertical-align property to “top” took care of the problem. I’ll be the first to admit that this isn’t the most elegant solution, but as far as I can tell, it works in every modern browser. Here is my final code:

pre, code, kbd, samp, tt, textarea{
	font-family: monospace, monospace;
	vertical-align: top;
}

Please let me know if you find any browsers that don’t render this properly. Thanks!

Posted February 25, 2012 by Alex Mansfield

2 responses to “Font-size and Line-height for <pre>, <code>, and Other Monospaced Fonts”

  1. Covi says:

    Hello and thanks for sharing 😉
    In my tests for inline elements (samp, tt…) within paragraphs, all monospaced fonts effectively break the baseline. Not the best solution but works.

    As for me I keep investigating, thanks again 😉

    PS: I use Compass Vertical Rhythm and modular scale 😉

    • alexmansfield says:

      Do they still break the baseline when using the method I mentioned? I admit it isn’t the best solution, but it appeared to work when nothing else would. Did you find a case where it didn’t work?

Leave a Reply

Your email address will not be published. Required fields are marked *

  • PublishedFebruary 25, 2012
  • Posted InCSS
  • DifficultyIntermediate