More Web Design Tutorials

CSS Shortcuts

March 12, 2011

Shortcuts are a good thing. They save time, gas, and make life easier. And who wouldn’t like things easier? Why write:

body {
background-color: #ffffff;
background-image: url(image/picture.jpg);
background-repeat: repeat-x;
background-position: top right;
}

if you could just write:

body {
background: #ffffff url(image/picture.jpg) repeat-x top right;
}

All this:

#example {
border-top-color: #cccccc;
border-top-width: 5px;
border-top-style: dashed;
border-left-color: #cccccc;
border-left-width: 5px;
border-left-style: dashed;
border-bottom-color: #cccccc;
border-bottom-width: 5px;
border-bottom-style: dashed;
border-right-color: #cccccc;
border-right-width: 5px;
border-right-style: dashed;
}

Could be written like this:

#example {
border: #cccccc 5px dashed;
}

Isn’t it beautiful?

But what if you don’t want all sides the same? No problem. These shortcuts work on all kinds of properties. Let’s use the margin for this example:

p {
margin-top: 5px;
margin-right: 10px;
margin-bottom: 15px;
margin-left: 20px;
}

Do take note of the order I have listed these properties in. When you list them out like I did here, the order does NOT matter, but I am using the top-left-bottom-right order for a reason: That’s how CSS is understood by your browser. So instead of all those lines up here, you could write:

p {
margin: 5px 10px 15px 20px;
}

If all 4 sides are the same – let’s go with 10px, just write:

p {
margin: 10px;
}

If your top and bottom are, for example, 20px but your right and left side 40px, you can write:

p {
margin: 20px 40px;
}

And, one last option:

p {
margin: 10px 40px 5px;
}

This would tell your browser to display the top margin as 10px, right and left side as 40px, and bottom as 5px.

In general, it’s a simple principle, and easy to remember – just think clock: noon, 3, 6, and 9 o’clock. Same order. For the longest time, so, I could not remember which sides this 3-dimensional shortcut referred to, until I realized that my head and my bottom are clearly of a different size, but my arms are the same length (well, almost).