Shorthand CSS is the method of writing related style properties all on one line instead of several. Using shorthand CSS results in files that are smaller in size and easier to read and maintain. Shorthand CSS is most commonly used on font, border, margin, padding and background styles. The easiest way to explain shorthand CSS is to give some examples.
The two examples above are both exactly the same. As with all shorthand usage, the important thing to remember is the correct order.
For margin, padding and border (which we’ll come to), top mirrors bottom and right mirrors left (the properties are listed in clockwise order: top, right, bottom, left) which means that, taking the margin example from above, we only need to specify two values if top and bottom are the same and left and right are the same.
With the padding example, all four are different so we specify each value. If all four were the same, it would look like:
padding: 1em;. If top and bottom were the different but left and right were the same, we could get away with only specifying three values:
padding: 0 0.5em 0.75em; (note that you don’t need to specify a unit if the value is 0).
Border is a little bit different because we need to also add
Quite clearly, shorthand CSS is most useful when styling borders – one line instead of 12! Of course, this is only if we want all four borders to be the same. What if we want them the same style and colour but different widths?
We use the first line to set the styles for all four sides then use the second line to give each side its own width. The same would apply if we wanted different styles and colours too:
Background properties are another handy one to shorten and their usage is straightfoward. The order of position and repeat seems to not matter although colour must come before the image. Remember when specifying the units for
background-position that horizontal comes first and vertical second.