Friday, October 28, 2011

TRouBLe is Useful

Web programmers have probably seen this a lot:
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left:20px;

The reason many programmers "need" 4 lines of code for such a simple thing, is that it's impossible to set the margin (margin is just an example, since this is also true for padding/border/...) to 20px, and then override just the top margin. But isn't there a better way?

Well, there is a shortcut for the above:
margin: 10px 20px;

Shorter, heh?
The parameters for attributes such as margin, are specified in this order: Top Right Bottom Left, or TRouBLe for short. CSS parsers are smart enough to apply the last specified parameters, to those that were omitted. So in the above example, I've omitted bottom and left, so the 20px value would be applied to those as well.
The general rule is:
* if only one value is specified - it is used for all (top, right, bottom and left)
* if two values were specified - the first will be used for top and bottom, and the second for left and right
* if thee values were specified - the first will be used for the top value, the second for the left and right values, and the last for the bottom value
If I wanted to set the margin-left to 10px, I'd have to write this "long" statement:
margin: 10px 20px 10px 10px;
Which is still shorter than the first example above.
Many times, the shortened syntax can be used, and save us some typing while increasing the expressiveness of CSS attributes.

EDIT: It seems I messed up a bit the order in which things are shortened. Thanks for Tomer for correcting me. I've updated the post accordingly.

4 comments:

  1. The first example is margin: 10px 20px 20px 20px; which isn't the same as margin: 10px 20px 20px 10px; or margin: 10px 20px;. 😄

    ReplyDelete
  2. actually, "margin: 10px 20px 20px 20px" is exactly like "margin: 10px; 20px". That's what this post was trying to explain.
    Omitting values from the TRBL list, will cause it to take the last value specified.

    ReplyDelete
  3. You wrong. margin: 10px 20px; is a shortcode for margin: 10px 20px 10px 20px;.

    http://www.w3.org/TR/CSS2/box.html#propdef-margin

    ReplyDelete
  4. I stand corrected. I'll fix the post. Thanks a lot.

    ReplyDelete