CSS Margins

Margin means the space between the content and its neighbouring content. There can be top margin, bottom margin, left margin, and right margin.

Margin - Individual Sides

CSS margin have different properties for each sides. So we can define margin for each side.

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

All the margin properties can have the following values:

  • auto - the browser calculates the margin
  • length - specifies a margin in px, pt, cm, etc.
  • % - specifies a margin in % of the width of the containing element
  • inherit - specifies that the margin should be inherited from the parent element

Tip: Negative values are allowed.

See the Pen css margins by Arpit (@soniarpit) on CodePen.

Margin - Shorthand Property

Instead writing individual properties for each side, you can also write it in one line.

The margin property is a shorthand property for the following individual margin properties:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

So, here is how it works:

If the margin property has four values:

  • margin: 25px 50px 75px 100px;
    • top margin is 25px
    • right margin is 50px
    • bottom margin is 75px
    • left margin is 100px

If the margin property has three values:

  • margin: 25px 50px 75px;
    • top margin is 25px
    • right and left margins are 50px
    • bottom margin is 75px

If the margin property has two values:

  • margin: 25px 50px;
    • top and bottom margins are 25px
    • right and left margins are 50px

If the margin property has one value:

  • margin: 25px;
    • all four margins are 25px

Margin Auto

You can set the margin property to auto to horizontally center the element within its container.

The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

See the Pen margin auto by Arpit (@soniarpit) on CodePen.

Margin Inherit Value

This example lets the left margin of the

element be inherited from the parent element (


See the Pen margin inherit by Arpit (@soniarpit) on CodePen.

Previous: CSS Borders

Next: CSS Padding