margin

Description

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.

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

Syntax and Property Values


margin: margin1 ... margin4 | inherit 

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

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.

Example


<!DOCTYPE HTML>
<html>
    <head>
        <style>
        body {<!-- ww w.  ja v a  2 s  . c o  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

The code above generates the following result.

margin




















Home »
  HTML CSS »
    HTML CSS Reference »




HTML Tag Reference
CSS Reference
CSS Selector Reference
Encoding Reference