CSS shorthand tips
In a lot of the CSS code I see, people don’t seem to be aware of shorthand properties. They are an excellent way of keeping your stylesheet condensed and it also gives you an easy overview. Basically, it’s a way to write one-liners to affect all sides of an element or all similar properties grouped together.
The general rule is to apply length values for padding, margin and borders. They are to be written in this order, according to the element’s sides: top, right, bottom, left. If you only write two values, it will be for: top/bottom and right/left. Write three values and it will be applied like this: top, right/left, bottom.
NOTE: Remember to always specify a unit, such as px, em, % etc, unless the value is 0.
/* 2 px margin all around */
div#header{
margin:2px;
}
/* 2 px top/bottom margin and 4 px right/left margin */
div#header{
margin:2px 4px;
}
/* 1 px top margin, 4 px right/left margin and 8 px bottom margin */
div#header{
margin:1px 4px 8px;
}
/*
1 px top margin, 3 px right margin, 8 px bottom margin
and 5 px left margin
*/
div#header{
margin:1px 3px 8px 5px;
}
W3C’s CSS 2.1 specification on margin properties, padding properties and border properties.
For font values, the shorthand property is applied in this order: font weight, font size/line height, font family.
/*
A bold font weight, 10 px big with a line height of 14 px
and desired font family specified in prioritized order.
The font weight value and the line height value can be omitted.
*/
div#header{
font:bold 10px/14px Verdana, Arial, Helvetica, sans-serif;
}
W3C’s CSS 2.1 specification on the font shorthand property.
When it comes to background styles, it comes in this order: background color, background image, background repeat, background attachment, background position. Like this:
/*
The element will get a white background and have
a non-repeated background image that is placed
in the element's top right corner.
*/
div#header{
background:#FFF URL(images/funky-pic.png) no-repeat right top;
}
W3C’s CSS 2.1 specification on background properties.
Using shorthand properties results in a compact CSS file whose weight in kbs will be as little as possible.
PS. A nod to Roger’s Efficient CSS with shorthand properties post, which I read after I wrote this. It contains more information for those of you who can’t get enough! DS.


