Fixing Monospaced Font Size With CSS Font Family
…Huh? What?
Last night I fixed the font size for monospaced segments on this website
by setting the font-family
CSS property
with this snippet:
code, kbd {
font-family: 'fix the damn font size', monospace;
}
…and it works. As intended.
Martin, what are you talking about‽
Let’s start with some context.
I strive to respect the aesthetic preferences of the person using the computer, and as part of that I choose not to specify the typefaces used on this website. If you dislike the typeface used to display this then… why did you choose it?
But since it’s sensible (and customary) to do so
I tag snippets of code or keyboard input
with code
and kbd
HTML elements, respectively,
and those traditionally get displayed with a monospaced typeface.
And I want those to be the same visual size as the surrounding text, like they are in basically every document on the planet.
I used to accomplish that by setting a global font-size
but then I was convinced that that is not a good idea.
But specifying relative font sizes didn't work
because they're calculated from different base values
for proportional and the default monospaced font.
Why? Ancient Browser Defaults!
Web browsers include built-in styles that they apply to every web page,
and parts of what that looks like can be configured in the browser settings.
For example, the “Advanced” font settings dialog looks like this on my computer today:
Notice those sizes: 16px for proportional and 12px for monospaced. Those are the default values, and have been for as long as I can remember.
And the effect is that if you specify a relative base font size on your page it will apply to one of those default font sizes.
Why does font-family
matter here then?
The reason this isn't more noticeable on other sites seems to be that this default monospace font size only applies to the default monospaced font and not to other monospaced fonts.
I imagine this is because the browser doesn't check beforehand
which of the fonts in the font-family
is going to match,
or whether the matching font is a monospaced or proportional one.
Which is reasonable,
computers disagree about which fonts they consider monospaced all the time.
And without that information it makes sense to fall back
to the larger, safer font size.
Conclusion
It doesn't matter which font family I choose:
as long as it's not just monospace
but in the end it matches only monospace
then I get the default monospaced font
but with the default font size for fonts
other than the default monospaced font.
Which is exactly what I want.