CSS Shorthand – The Need to Know Basics

Posted on February 8, 2009

Short hand CSS has made my coding days so much easier and faster, but even I don’t take full advantage of shorthand code- mainly becuase I didn’t know it was possible until experimenting with it. Here are some CSS shorthand guides you can use to make your life easier.

Shorthand Padding and Margin:
Yeah this is a simple one, but all too often people forget to use it and end up typing way more CSS markup than is needed.

#element {
  padding-top: number+unit;
  padding-right: number+unit;
  padding-bottom: number+unit;
  padding-left: number+unit;
}

You can save alot of time, just think of the hands of a clock starting at noon, and follow around clocking wise, top right bottom and left. Padding and Margin work exactly the same.

#element {
  padding: value value value value;
}

Background:
This could be my all time favorite short hand property in CSS

#element {
  background-color: color || #hex || (rgb / % || 0-255);
  background-image:url(URI);
  background-repeat: repeat || repeat-x || repeat-y || no-repeat;
  background-position: X Y || (top||bottom||center) (left||right||center);
  background-attachment: scroll || fixed;
}

The cool thing about this shorthand method is that these properties can be combined.

#element {
  background:
    #fff
    url(image.png)
    no-repeat
    20px 100px
    fixed;
}

You can leave out as many values as you want, but they will automaticaly inheret their default values. They are as follows: Background-color: defaults to ‘transparent’, background-image: defaults to ‘none’, background-repeat: defaults to ‘repeat’, background-position: defaults to ‘top left’, and background-attachment: defaults to ’scroll’.

Border Properties:

#element {
  border-width: number+unit;
  border-style: (numerous);
  border-color: color || #hex || (rgb / % || 0-255);
}

You can trim this bad-boy down pretty easily

#element {
  border:
    6px
    solid
    #3f3f3f
}
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • TwitThis
  • email

1 Response

  1. Shane Riley
    February 9, 2009

    You should add the font shorthand property. You can go from:
    * { font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    line-height: 140%;
    font-weight: bold;
    font-style: italic;
    font-variant: small-caps; }
    to:
    * { font: italic small-caps bold 12px/140% Arial, Helvetica, sans-serif; }

    When I’m brought in to clean up CSS, this is the one that’s always set to longhand.


Leave a Reply