CSS Property margin

margin shorthand property sets the width of the overall margin for an element or sets the widths of each individual side margin. Vertically adjacent margins of block-level elements are collapsed. The left and right margins of inline elements do not collapse. Negative margin values are permitted.


Inherited No.
Version CSS1
JavaScript syntax object.style.margin="10px 5px 10px 5px"
Applies to All elements.

margin can have one to four values.

margin:10px 5px 15px 20px;

is equal to

  • top margin is 10px
  • right margin is 5px
  • bottom margin is 15px
  • left margin is 20px
margin:10px 5px 15px;

is equal to

  • top margin is 10px
  • right and left margins are 5px
  • bottom margin is 15px
margin:10px 5px;

is equal to

  • top and bottom margins are 10px
  • right and left margins are 5px

is equal to all four margins are 10px.

Negative values are allowed.

CSS Syntax

margin: margin1 ... margin4 | inherit 

Property Values

The property values are listed in the following table.

auto Default value. The browser does the calculation.
length Set width in px, cm, etc.
% Set width in percent of the containing element
inherit Inherit the width property from the parent element

Browser compatibility

margin Yes Yes Yes Yes Yes


An example showing how to use margin CSS property.

        body {<!--from  www. jav a  2  s . co m-->
            margin: 0;
            padding: 0;
        div {
            width: 100px;
            height: 100px;
            background: mistyrose;
            border: 1px solid pink;
        div#topbottom-rightleft-1 {
            margin: 15px 5px;
        <div id='topbottom-rightleft-1'></div>

Click to view the demo