Thursday, February 11, 2010

CSS: Using font shorthand

Using CSS shorthand simplifies your code, produces smaller, more efficient documents and can save time. 

I often use shorthand for margin, background, border and padding elements. I tend not to use it for font because it can be a bit tricky and I'm generally only changing one or two attributes at a time.

Today I was reviewing someone else's HTML/CSS and I noticed that the main body of text didn't look quite right in Chrome and Firefox. Instead of Verdana, which displayed correctly in IE, it seemed to be rendering as a generic serif-based font.

After a bit of investigating and head-scratching it transpired that this line was the culprit:

font: { 0.8em lighter; }

The problem is the placement of the word "lighter", in this case used to set the font-weight.

The following attributes can be used to style fonts, using the font shorthand:


The first three of these are optional and can be placed in any order. Line-height is also optional and is appended to font-size with a separating '/'.

Font-size and font-family are not optional. Actually, I thought that font-size was optional but when I removed it the font declaration disappeared from my debugger.

So, in the example above, "lighter" is being taken as the font-family. As this is not a recognised family, the text default was being used.

The correct version of the above declaration is

font: { lighter 0.8em Verdana, Geneva sans-serif; }

or whichever font stack you'd prefer to use.

In the event, it transpired that this declaration was not required. A font-weight of normal achieved the same as lighter in this case. Removing font-weight from the declaration forces the default, which is normal, leaving:


font: { 0.8em Verdana, Geneva sans-serif; }


Additionally, font-family was already being set in the body style and wasn't being redefined anywhere. Then there was a global p declaration, which was only setting color. I added the font-size attribute to this element and it all worked in every browser. 

Of course, the actual solution will depend upon the individual CSS and inheritance but the basic principle is this: 

if using font shorthand, always include font-size and font-family respectively.

If you don't wish to define either of these elements then style your attributes individually rather than using shorthand.

No comments:

Post a Comment