Posted: Mon Oct 22, 2007 5:30 am Post subject: CSS Shortcuts
When writing your CSS, it is possible to write neater, more readable code by making use of CSS shortcuts. A shortcut is a feature of CSS that allows the developer to specify a number of related properties on a single line rather than specify them all separately. Lets look at the following example:
The code above is perfectly valid and will work fine, but we can save time and make the code much neater using the following code:
Code:
.header {
padding:5px 10px 5px 10px;
}
Using the code above we can specify all of the padding for the header div on one line. It works by applying the first attribute (5px) to the top padding of the div. The second (10px) applies to the right side padding, the 3rd (5px) attribute means the padding on the bottom of the div, and the forth (10px) attribute means the left side padding. The padding is always applied in this order.
It is possible to shorten this code even further using the following code:
Code:
.header {
padding:5px 10px;
}
This works by taking the first (5px) attribute to mean the top and bottom, or vertical padding, and the second (10px) attribute to mean the horizontal padding (left and right).
The exact same principles can be used to declare the margin of your divs, so what could have looked like this:
The above code is much quicker and more manageable. Take note though, that all of the properties must be provided when using the background shortcut. If I missed off the color specification at the beginning for example, the code would not work.
Font shortcuts
Another very useful shortcut is the font shortcut. The code below can be shorted considerably:
body {
font: bold 0.8em/1.2em verdana, sans-serif;
}
It is important to write the shortcut in the same order as above so that web browsers don’t get confused!
Borders
This is my favorite shortcut of all. This saves me a great deal of time when I am developing web sites because whenever I have a problem with a layout or an element, the first thing I do is put a border around it so that I can see its dimensions and work out what’s going on.
Then, whenever you are not sure why an element is not behaving properly, just use the border shortcut above to debug your code and see what the dimensions of the element are.
Conclusion
As you can see, you can make your code much shorter and neater using the CSS shortcuts outlined here. Once you get into the habit of using them, I guarantee that you will wonder why you ever did it differently in the past!
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum