Home » CSS: Use Shorthand Properties

CSS: Use Shorthand Properties

Summary:

Use shorthand properties in CSS to shrink your style sheets.

Shorthand properties allow you to specify a set of related CSS properties with a single property. They combine related properties into a shorthand form. In most cases, the browser sets a default value if you leave out an optional one. There are six shorthand properties in CSS:

  • font
  • background
  • margin
  • border
  • padding
  • list

The most commonly used properties are the font family of properties. With the font shorthand property you can turn this complete declaration:

p {
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: .9em;
line-height: 1.1em;
font-family: arial, helvetica, sans-serif;
}

Into this:

p {font: italic small-caps bold .9em/1.1 arial,helvetica,sans-serif;}

In most cases you’d specify just the size and face, like this:

p{font:.9em arial,helvetica,sans-serif;}

Padding and Margin Shorthand Properties

Instead of specifying up to four longhand padding or margin values, you can use the padding and margin shorthand properties. So instead of this:

div {
padding-top:1em;
padding-right:2em;
padding-bottom:1em;
padding-left:2em;
}

You can do this:

div{padding:1em 2em;}

Note that these values replicate according to the CSS specification when values are omitted. For our example above the top and right values replicate to the bottom and left padding respectively. The margin and border shorthand properties uses the same syntax.

Border Shorthand Properties

The border properties have eight shorthand properties (border-style/width/color, border-top/right/bottom/left and border). The most powerful is the border shorthand property which you can use when all sides of your element have the same values. So instead of this:

div {
border-top: thin solid red;
border-right: thin solid red;
border-bottom: thin solid red;
border-left: thin solid red;
}

You can do this to create a thin red line:

div{border:thin solid red;}

You can use border properties in combination to null out each other to save space and create effects. For example:

div {
border:1px solid black;
border-top:0;
border-right:0;
}

This abbreviated form of specifying style is supported by most modern browsers. You can combine shorthand properties with grouping to save even more. We’ll cover grouping in an upcoming tweak.

Further Reading

CSS Home Page
From the W3C
CSS Optimization
Summary of chapter on optimizing CSS from Speed Up Your Site: Web Site Optimization.
Cascading Style Sheets, level 2 CSS2 Specification
The CSS specification, from the W3C. By Bert Bos et al.
CSS Support Charts
Eric Meyer. The master CSS reference grid.
CSS: The Definitive Guide
Eric A. Meyer, (O’Reilly, 2000). A great introduction to CSS which includes descriptions of these shorthand properties. See also Meyerweb.com.

Leave a Comment