Archive for April, 2015

Quotes and font names


One popular misunderstanding about specifying fonts in CSS is that you should put quotes around the name of the fonts when they contain spaces, and you shouldn’t when they don’t. And you end up with this

font-family: "Hoefler Text", Utopia, "Liberation Serif", Times, "Times New Roman", serif;

This usage, however, is flawed.

Not only is this an oversimplification of the rules, but there are many instances in which the opposite is true! So, some clarification is in order.

First, the official rules.

You MUST use quotes if

  1. A font name starts or ends with a space, or it has runs of two or more adjacent spaces in its name, or it contains other whitespace characters such as tabs.
  2. The name contains characters that can confuse the parser into thinking the property ends there, like a comma, a semicolon etc.
  3. The name happens to be a keyword that would otherwise be handled differently, such as inherit.

And you MUST NOT use quotes if

  1. You are specifying one of the generic font-families serif, sans-serif, monospace, cursive or fantasy
  2. You don’t mean a font name, but rather an action such as inherit.

In all other cases, quotes are optional.

So first of all, an important conclusion to draw is that font names like Times New Roman are perfectly safe to use without quotes. No weird characters in the name, no two spaces in a row etc. You can test this for yourself; all browsers handle this name the same whether you include quotes or not; the W3C CSS Validator finds no errors etc.

So spaces are not a problem, really. You know what’s a problem? Numbers! If you have a font named Courier 10 Pitch, you’ll have to put quotes around it or it won’t show.

Then there’s the other thing: using one-word font names without quotes. The point is, how will you know that your font name is not a keyword? Like I said above, if you have a font named Inherit, you must put quotes around it or the parser will think you meant to inherit the font from the parent element.

And there are more such keywords. Font names like Default, Caption, Icon, Menu, Message-Box, Status-Bar and so on are all problematic.

And not only are there many such keywords, there are also new keywords invented regularly. For example, the words initial, unset and revert are relatively new. So if you had a font named Initial or UnSet, you could use its name without quotes until a few years ago, but you no longer can!

What can we learn from all of this? Simple: play it safe. Put all font names in quotes. The quotes won’t do any harm, even where they’re not needed, but leaving them out to save two bytes in your source will come back and bite you in the rear later!