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.

Summary

ItemValue
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
margin:10px;

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.

ValueDescription
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




Example

An example showing how to use margin CSS property.

<!DOCTYPE HTML>
<html>
    <head>
        <style>
        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;
        }  
        </style>
    </head>
    <body>
        <div id='topbottom-rightleft-1'></div>
    </body>
</html>

Click to view the demo