August 10, 2010

CSS Shorthand

For all of you CSS coders who are pretty lazy (myself included), you can use CSS shorthand to type out certain properties in one line instead of many many lines. Here's an example:

Say you want to add a background image to your fancy new website using CSS. And it should not repeat. And the position should be on the top left. Oh, and you also want to add a background color because parts of your image are transparent.

Instead of tediously typing this out:

background-color: #ccc;
background-image: url('../images/background.png');
background-repeat: no-repeat;
background-position: top left;

You can simply do this:

background: #ccc url('../images/background.png') no-repeat top left;

Not only does this save you from having carpal tunnel in the future, but it makes your CSS files smaller so they take less time to load as resources = less loading times for your website. It's a win-win for everyone!



background: #ccc url('background.png') no-repeat left top;

Be careful -- these need to be in the correct order and if you omit any, the browser will use the default values for each property which may not be what you were expecting.



/* These two are equivalent */
font: normal normal bold 13px/11px Helvetica, serif;
font: bold 13px/11px Helvetica, serif;

Same deal as for backgrounds -- anything that is omitted gets applied the default property value. When in doubt, specify those values! There's another handy CSS shorthand guide here that lists various default values for different shorthand properties as well.

These next couple are pretty straight forward:


/* Remember this as clockwise from the top */

margin: 1px 2px 3px 4px;


     [margin-right AND margin-left]

margin: 1px 2px 3px;


     [margin-top AND margin-bottom]
     [margin-right AND margin-left];

margin: 1px 2px;


margin: [margin for all sides];

margin: 1px;

The same goes for padding properties.

padding: 1px 2px 3px 4px;



border: 1px red solid;