CSS Margin

Wednesday, March 21, 2012

tags CSS

CSS Margin defines the space surrounding an element. This space is transparent, is outside the border of the element, and does not have a background color. You can define the entire margin around an element or define the top, bottom, right and left margins independently. There is also a shorthand margin property so that you can define all the margins at once.

Margin Property (Shorthand)

When using the shorthand margin property, set the values as follows: top, right, bottom, and left. For example:

p {margin: 1px 2px 3px 6px;}

If you want to apply the same margin to all four sides, you just use one value:

p {margin: 10px;}

If you want the margin to be the same for the top/bottom and left/right, you use two values:

p {margin: 10px 20px;}

Using three values, you will set the left and right margin the same, while setting the top and bottom with different values:

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

If the margin is set to zero, then it has the same edge as the element. You should note that margin can be set using a non-negative value. This may cause elements to overlap. You can specify the measurement as px, pt, em, in, cm, etc. You can also specify a percentage for your margin, which will be a percentage of the width of the element’s containing block. You can also set the margin to auto and allow the browser to determine the optimal margin value.

Margin Individual Sides

As mentioned earlier, in CSS, it is possible to specify different margin values for each side of the HTML element:

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

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

HTML CSS: The Complete Reference HTML CSS and JavaScript Editor CSS: The Missing Manual