CSS Margin

This margin property is used to define the space around elements. It is completely transparent and doesn’t have any background color. It clears an area around the element.

We can have top, bottom, left and right margin which can be changed independently using separate properties. We can also change all properties at once by using shorthand margin property.

Property         Description
marginThis property is used to set all the properties in one declaration.
margin-leftit is used to set left margin of an element.
margin-rightIt is used to set right margin of an element.
margin-topIt is used to set top margin of an element.
margin-bottomIt is used to set bottom margin of an element.

There are different type of margin values supported:-

Value  Description
autoThis is used to let the browser calculate a margin.
lengthIt is used to specify a margin pt, px, cm, etc. its default value is 0px.
%It is used to define a margin in percent of the width of containing element.
inheritIt is used to inherit margin from parent element.

Note: We can also use negative values to overlap content.

Input:-

Index.html
	
<body>
	  <div>
		This is a div element
	 </div>
</body>

Style.css
	
div {
    margin-top: 50px;  
    margin-right: 100px;  
    margin-bottom: 150px;  
    margin-left: 200px;  
}

Output:-

The Margin Shorthand Property

The margin property is a shorthand property to avoid setting padding of each side separately, i.e., margin-top, margin-right, margin-bottom and margin-left.

h1 {
    margin: 50px; /* apply to all four sides */
}
p {
    margin: 25px 75px; /* vertical | horizontal */
}
div {
    margin: 25px 50px 75px; /* top | horizontal | bottom */
}
pre {
    margin: 25px 50px 75px 100px; /* top | right | bottom | left */
}

Below example illustrate the use of margin properties with single property use.

Input:-

Index.html
	
<body>
	  <div>
		This is a div element
	 </div>
</body>

Style.css
	
div {
    margin: 50px 100px 150px 200px;  
}

Output:-

Horizontal Centering with Auto Margins

The auto value for the margin property tells the web browser to automatically calculate the margin. This is commonly used to center an element horizontally within a larger container.

Input:-

Index.html
	
<body>
	  <div>
		This is a div element
	 </div>
</body>

Style.css
	
div {
	   width: 200px;
    background: gray;
    margin: 0 auto;
}

Output:-

The above style rules lets the <div> element take up 200 pixels of all the horizontal space available, and the remaining space will be equally divided between left and right margins.