Monday, September 13, 2010

Working with CSS shorthand for boxes

Both of the previous two code examples use CSS shorthand, and this is something that is
useful to get to grips with, in order to create the most efficient and easy-to-update CSS.
The previous example showed how to set all margins and padding values to 0, and this was
done in shorthand instead of writing out every single value. How CSS shorthand works for
boxes is like this:
A single value (margin: 10px;): This is applied to all edges.
Two values (margin: 10px 20px;): The first setting (10px) is applied to the top and
bottom edges. The second setting (20px) is applied to both the left and right edges
(20px each, not in total).
Three values (margin: 10px 20px 30px;): The first setting (10px) is applied to the
top edge. The second setting (20px) is applied to both the left and right edges. The
third setting (30px) is applied to the bottom edge.
Four settings (margin: 10px 20px 30px 40px;): Settings are applied clockwise
from the top (i.e., top: 10px; right: 20px; bottom: 30px; left: 40px).
Shorthand’s benefits become obvious when comparing CSS shorthand with the equivalent
properties and values written out in full. For instance, the following shorthand
#box {
margin: 0;
padding: 0 100px;
}
looks like this when written out in full:
#box {
margin-top: 0;
margin-right: 0;
margin-bottom: 0;
margin-left: 0;
padding-top: 0;
padding-right: 100px;
padding-bottom: 0;
padding-left: 100px;
}
Whether or not you use shorthand is up to you. Some designers swear by it and others
because of it. Some web design applications have options to “force” shorthand or avoid it
entirely. I reckon it’s a good thing: CSS documents are usually more logical and shorter
because of shorthand. But if you don’t agree, feel free to keep on defining margins and
padding as relevant for every edge of every element.

No comments:

Post a Comment