CSS shorthand tips
I wrote this post a while back. The content can still be relevant but the information I've linked to may not be available.
The increasing use of CSS for web design has meant that most websites have one (or several) stylesheets. Stylesheets are being used extensively, they can become quite large and it makes sense to make them as concise as possible. Shorthand CSS can make a big difference to the size of the stylesheet on larger websites and it can help to make any stylesheet easier to use.
We are increasingly using stylesheet shorthand ourselves, so here are a few tips – mostly derived from our experience with editing long stylesheets!
Tip 1 – Font duplication
Firstly, there’s no need to specify the font-attribute for every element in your stylesheet. It’s easy to do this. We’ve done it ourselves! If you specify the font for <body> like this…
font-family: Georgia, “Times New Roman”, Times, serif;
... all other <body> elements like <p> will inherit this font (unless you say otherwise). This alone will save a lot of Kbs in your stylesheet. Great! Of course, you can still easily change the font for a specific element, eg for headers like <h1>, by adding in a new rule like:
font-family: Verdana, Arial, sans-serif;
The guideline here is to add styles only when necessary. Get rid of duplication if it does not add anything.
Tip 2 – Colour notation
Another tip, if you use hexadecimal colors like this, #000000, with identical number pairs, they can be shortened in your stylesheet by omitting the second number in each pair. For example, this website uses #6699CC as one of its main colors. This can be shortened to #69C – and it will have the same effect.
Tip 3 – Combining properties
Suppose we want to set a margin for our paragraphs. We could define it like this in the stylesheet:
However, the shorthand form here is equally valid and looks neater to our eyes:
margin: 2em 4em 2em 10em;
How do I know which value refers to top or bottom or left or right? Well, the order is always top-right-bottom-left. It’s easy to remember after you use it a few times. Think of it in clockwise order starting from 12 o’clock.
In conclusion, we are always learning ourselves and we’d be the first to admit that our websites do not always use CSS shorthand. However, this article was inspired by the fact that we are gradually improving the stylesheets for several websites (including this one!) using these tips. Try them for yourselves!