Thursday, February 02, 2006

Compact your CSS code

Another aspect of Optimization is compacting the code itself. There are two different aspects to compacting -- using CSS shorthand and reducing white space in the final HTML file. Today's topic deals with compacting CSS by use of shorthand.

Basically, CSS "shorthand" means that you can combine several different element attributes into one line. An example of one that should get heavy use is "font". You can specify the font weight, size, and family separately or all together, as a shorthand version. Here's a long version:

H1 {
font-weight: bold;
font-size: 0.9em;
font-family: arial, sans-serif;
}

And here's the same CSS but using shorthand:

H1 {
font: bold 0.9em arial, sans-serif;
}

The second (shorthand) method uses less code. Reducing code this way speeds up the display time for the affected page. If the CSS code is in a separate (external) style sheet affecting several pages, you get the benefit across those pages from just one editing session.

For more on code optimization, see "CSS Semantics and Optimisation" on the "Develop the Web" site.

For an "Introduction to CSS Shorthand", try that part of the SitePoint site. Other good pages include the CSS Shorthand Guide and CSS Shorthand Properties. And remember to always go to the "source" -- the World Wide Web Consortium's CSS pages. ... Not for the faint of heart, perhaps, but if you look over the information, you'll have plenty of ideas to try out.

No comments: