Документация
HTML CSS PHP PERL другое

Margin Shorthand

 
Previous Page
Table of Contents
Next Page

Margin Shorthand

Margin properties have a shorthand counterpart using the margin property. You'll have noticed that CSS shorthand properties tend to have quirks of their own, such as the order of values. Margins are no exception to this.

Using the margin property, you set up the values for your margins in this exact order: top, right, bottom, left. The popular mnemonic for this in the industry is "TRouBLe." In Example 11-3, I'd set all the longhand properties for the body:

body {margin-top: 30px; margin-right: 30px; margin-bottom: 30px; margin-left: 130px;}

Although longhand doesn't require the specified margin order, I thought it would be helpful for you to see how this translates to shorthand:

body {margin: 30px 30px 30px 130px;}

You'll note that there are no commas separating each value, and the values will be applied in the exact TRBL order.

But wait, there's more. You can shorten your shorthand by relying on the fact that opposite side values automatically take their counterpart's value if they are not set:

Body {margin: 30px 20px}

That results in 30 pixels top and bottom, and 20 pixels right and left. So what happens when there are three values?

body {margin: 30px 20px 70px;}

The left value takes from the right, so this results in a margin of 30 pixels top, 20 pixels right, 70 pixels bottom, and 20 pixels left.

If all your margins are of equal size, simply use the value once:

body {margin: 100px;}

This results in a 100-pixel margin for all sides of the body element.

You also can use percentages as well as width values:

body {margin: 20%}

That results in a margin of 20% all the way around. Finally, remember that you do not need to define length or percentages if your value is 0:

body {margin: 0 30px 20px 0;}

    Previous Page
    Table of Contents
    Next Page
    © 2000- NIV