The Shorthand CSS Notation Explained – Back to The Basics

Welcome to the first part of the Back to The Basics series of articles here on Scarf*oo. In this series, I’ll focus – in simple terms – on the basic stuff every web developer should be familiar with. Today, we’ll be looking at the shorthand CSS notation, a quick way to write long CSS statements in one short line.

The Regular Notation

To begin with, let’s look at all of the four margin properties written the standard way, long and time-consuming:

div {
    margin-top: 10px;
    margin-right: 5px;
    margin-bottom: 10px;
    margin-left: 5px;
}

Also, let’s write down a more complex definition – an element’s background property – in its glorious five components.

div {
    background-color: transparent;
    background-image: url(background_image.gif);
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: left top;
}

While writing the properties the long way is simpler and more descriptive to beginner web developers, you’ll soon find out that you are writing a lot of redundant code that way. That’s why there is a standard shorter syntax designed to overcome this issue.

The Shorthand Notation

Let’s try now to write down the margin and background properties the short way to save some space and keyboard mileage.

div {
    margin: 10px 5px 10px 5px;
}

One thing to learn here is the order of the properties written in the shortened statement above. They always run clockwise, starting with the top property (twelve o’clock), then right (three o’clock), then bottom (six o’clock) and lastly left (nine o’clock). Be sure to remember that basic rule!

That’s short, yet we can make that margin definition even shorter, taking advantage of the particular values our properties were set to, like this:

div {
    margin: 10px 5px;
}

The margin definition above can be shortened like that, because of the matching top & bottom and left & right values. This is valid for any CSS property which has a top, right, bottom and left value, like padding, border, etc.

You could shorten the margin property even further if all of the four margin sides were identical, say 10px like so:

div {
    margin: 10px;
}

Note, that you can also drop the trailing semicolon from the last property in a block. It’s not much, but just so you know that you can let it go if you want. Another space saver is to write a one-property block, like the one above in a single line. Let’s take a look now at our final super-short statement:

div { margin: 10px }

What about the background property? Using our new knowledge, we can make it really short:

div { background: white url(background_image.gif) no-repeat fixed left top }

That’s all I’ve prepared for you in this first part of Back to The Basics. Make sure to follow this series as I have many things to show you as we move along.