Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

CSS Shorthand

These are techniques for condensing, combining, and shortening your CSS code. Used wisely, they can make your stylesheets smaller (so they will load a little faster) and easier to read.

Grouping selectors

For example:

h1 {margin:0; font-weight:bold; font-size:130%; color:blue;
       padding-left:5px; padding-top:10px}
h2 {margin:0; font-weight:bold; font-size:120%;
       color:navy; padding-left:5px}
h4 {margin:0; font-weight:bold; font-size:105%;
       font-style:italic; color:blue; padding-top:1.5em}

The mouth-full of code above can be condensed into something a little more manageable. As shown below, CSS permits grouping selectors and giving them a shared declaration. See how the selectors can be grouped on one line with commas as separators?

h1, h2, h4 {font-weight:bold}
h1, h4 {color:blue}
h1, h2 {padding-left:5px}
h1, h2, h4 {margin:0}
h1 {font-size:130%;padding-top:10px}
h4 {padding-top:1.5em;font-size:105%;font-style:italic}
h2 {font-size:120%;color:navy}

Shorthand properties

CSS shorthand properties set several related properties with one declaration. The most common are background, border, font, padding, and margin.

Lengths for margins, padding, and borders are sequenced in clock-wise positions: top, right, bottom, left, e.g. :

.box {margin-top: 10px; margin-right: 20px; 
     margin-bottom: 10px; margin-left: 20px; }

Consolidate all of that into CSS shorthand and it abbreviates to:

.box {margin: 10px 20px 10px 20px; }

There are other modifications you can use when the margin values are repeated. In the example above, the top and bottom margins of 10px, and the left and right margins of 20px, would condense to:

.box {margin: 10px 20px}

If you wanted to use the above example, but have no bottom border, you could also use the following code:

.box { margin: 10px 20px 0; }

You can also streamline your border codes. Here is a border CSS code for a box:

.box {border-top: 1px; border-right: 1px; border-bottom: 1px; 
     border-left: 1px; border-color: blue; border-style: solid}

This can all be consolidated down to the CSS shorthand of:

.box {border: 1px blue solid}

Not all CSS codes can be grouped and condensed, but this article has described the most common ones.

CSS Shorthand Resources