Gotchas With the Font Shorthand Property



CSSThe font shorthand property is an easy way to specify a number of individual font properties at once. But you need to be careful how you use it or you may get unexpected behavior.


Let's go over the basics. The font shorthand property allows you to specify the font style, the font weight, the font variant, the font size and the font family. Some of these attributes are required while some of them aren't. Some of them it matters what order they are in, and for some of them it doesn't.
First, the font-size and the font-family are required values. If you leave those out, your entire rule is ignored. See below.
div
{
    font: 18px; /* Illegal style! */
}

span
{
    font: italic bold serif; /* Illegal style! */
}

In the above examples, your style is invalidated-and none of the properties are applied.
Secondly, the font-family must come last. This makes sense when you consider that this style rule may have a number of space-separated values itself. The font-size must come second-to-last.
The font-variant, font-style and font-weight are optional attributes, and it doesn't matter what order they are presented in, as long as they are before font-size and font-weight. See below.
div
{
    font: italic bold small-caps 18px Georgia, serif;
}

This seems pretty straightforward, but there is still a serious gotcha to be aware of. See below.
h1, h2
{
    font: italic bold small-caps 18px Georgia, serif;
}
h1
{
    font: 36px Georgia, serif;
}

If you were to try the above styles, you'd notice that h1 isn't bolded at all. Why is this the case? The problem is that although font-style, font-variant, and font-weight aren't required, if you leave them out they fall back on their default values which is normal. So...
h1
{
    font: 36px Georgia, serif;
}

is really the equivalent of
h1
{
    font: normal normal normal 36px Georgia, serif;
}

You really don't run into problems like this when you use the individual font properties since a lack of a property isn't considered the equivalent of one with a normal setting (typically in those cases, normal CSS inheritance rules apply).


No comments :