Margins

The CSS margin properties are used to create space around elements, outside of any defined borders.

CSS has properties for specifying the margin around an entire element or for each side of an element with properties.

  • margin
  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

All the margin properties can have the following values:

  • auto - browser calculates the margin
  • length - margin specified as px, pt, cm, etc.
  • % - margin specified as % of the width of the containing element
  • inherit - margin inherited from the parent element

Example: Specifying margins for a paragraph


		p {
		  margin-top: 		100px;
		  margin-bottom: 	100px;
		  margin-right: 	100px;
		  margin-left: 		100px;
		}
	

Output:

margins.png

Run it now


The above CSS code can be written in an abbreviated manner as shown below.


	p {
	  margin: 100px 100px 100px 100px;
	}
	

The first 100px is the top margin, followed by the right margin, bottom margan and, lastly, the left margin (clockwise).


If all the values are the same, the CSS code can be even further abbreviated to this..


	p {
	  margin: 100px;
	}
	

Example: Centering Content using a Div and Auto

The auto value will horizontally center content within its container.


		div {
		  width:	200px;
		  margin: 	auto;
		  border: 	1px solid green;
		}
	

Output:

margins2.png

Run it now