CSS Margin


The CSS margin property defines the space around the element.


Margin

Margin clear the surrounding (outer border) element area. The margin has no background color and is completely transparent.

Margin can change the top, bottom, left, and right margins of an element individually, or change all attributes at once.

CSS Margin

Possible Values

value Description
auto Set browser margins.
The result of this will depend on the browser.
length Define a fixed margin (using pixels, pt, em, etc.)
% Define a margin using percentage

Remark Margin can use negative values, overlapping content.


Margin - Unilateral Margin Attributes

In CSS, it can specify different margins on different sides:

Example

margin-top:100px;
margin-bottom:100px;
margin-right:50px;
margin-left:50px;

 Try It! 


Margin Shorthand Attribute

In order to shorten the code, it is possible to use all the margin properties specified by margin in one property. This is the so-called shorthand attribute.

The shorthand property for all margin properties is margin :

Example

margin:100px 50px;

 Try It! 

The margin property can have one to four values.

  • margin:25px 50px 75px 100px;

    • Top margin is 25px

    • The right margin is 50px

    • 75px bottom margin

    • 100px left margin

  • margin:25px 50px 75px;

    • Top margin is 25px

    • 50px left and right margins

    • 75px bottom margin

  • margin:25px 50px;

    • The top and bottom margins are 25px

    • 50px left and right margins

  • margin:25px;

    • All 4 margins are 25px



Examples

More Examples

The top margin of the text is set using centimeters

This example demonstrates how to set the top margin of a text that uses centimeters.

Use a percentage value to set the bottom margin
This example demonstrates how to set the bottom margin using a percentage value, relative to the width of the contained element.


CSS Margin Properties

Property Description
margin Shorthand attribute. Set all margin properties in one statement.
margin-bottom Set the bottom margin of the element.
margin-left Set the left margin of the element.
margin-right Set the right margin of the element.
margin-top Set the top margin of the element.