This website may use cookies. More info. That's Fine x
Welcome Login

Css: margin


Margin:

The margin clears an area around an element (outside the border). The margin does not have a background color, and is completely transparent.

A shorthand margin property can also be used, to change all margins at once.  The top, right, bottom, and left margin can be changed independently using separate properties.

 

 

margin property:

The margin shorthand property sets all the margin properties in one declaration. This property can have from one to four values.

Note: Negative values are allowed.

Property values:

Value      Description

auto       browser calculates a margin
	
length     specifies a margin in px, pt, cm, etc. Default value is 0px
	
%          specifies a margin in percent of the width of the containing element
	
inherit    specifies that the margin should be inherited from the parent element

 

 

Egs:

margin:10px 5px 15px 20px;

top margin is 10px
right margin is 5px
bottom margin is 15px
left margin is 20px

 

margin:10px 5px 15px;

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

 

margin:10px 5px;

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

 

margin:10px;

all four margins are 10px

 

Eg2: To center a containing block on a page, add auto margins to left and right of the containing block:

<!DOCTYPE html>
<html>

<head>
  <style type="text/css">
  div#structure {
    width: 300px;
    height: 100px;
    margin: 50px auto 5px;
    border: 1px solid red;
  }
  
  div#structure2 {
    width: 300px;
    height: 100px;
    margin: 50px;
    border: 1px solid red;
  }
  </style>
</head>

<body>
    <div id="structure">
    </div><br/>
    
    <div id="structure2">
    </div>
</body>
</html>

 

Outputs:

css-margin1

 

 

 

Margin: individual sides:

margin-top         Sets the top margin of an element

margin-right       Sets the right margin of an element

margin-bottom      Sets the bottom margin of an element

margin-left        Sets the left margin of an element

Created on: Monday, November 12, 2012 by Andrew Sin