CSS margin Property

CSS margin property specifies the margin for all four sides of an element in a single declaration.

A margin is defined as a transparent space around an element, outside of any defined borders that is used to set a gap between any two consecutive elements.

CSS margin property is a shorthand of the following properties:

The margin property can accept 1 to 4 values at a time. Let’s discuss each in detail:-

If only one value is specified:

  • margin: val;

The same value(val) is used for all four sides(top, right, bottom and left) of margin. Try out the example below to see how it works:

Example:

div{
  margin: 50px;
}

If two values are specified:

  • margin: val1 val2;

The first value(val1) is used for the top and bottom margin, and the second value(val2) is used for the left and right margin. Try out the example below to see how it works:

Example:

div{
  margin: 100px 50px;
}

If three values are specified:

  • margin: val1 val2 val3;

The first value(val1) is used for the top margin, the second value(val2) is used for the left and right margin, and the third value(val3) is used for the bottom margin. Try out the example below to see how it works:

Example:

div{
  margin: 100px 70px 50px;
}

If all four values are specified:

  • margin: val1 val2 val3 val4;

The first value(val1) is used for the top margin, the second value(val2) is used for the right margin, the third value(val3) is used for the bottom margin and the last value(val4) is used for the left margin. Try out the example below to see how it works:

Example:

div{
  margin: 100px 70px 50px 30px;
}

CSS Syntax

The margin property has the below syntax:

margin: margin-top margin-right margin-bottom margin-left|auto|initial|inherit;

Property Values

The margin property accepts the following values:

margin-topSpecifies the margin for the top of the element.
margin-rightSpecifies the margin for the right side of the element.
margin-bottomSpecifies the margin for the bottom of the element.
margin-leftSpecifies the margin for the left side of the element.
autoThe browser automatically calculates the margin.
initialSets the margin property to its default value.
inheritInherits the margin from its parent element.

General Info

Default Value0
InheritedNo
JavaScript Usageelement.style.margin= “50px 60px”;