Categories
CSS Tutorials

Margins

CSS Margins

This property will create white space around the HTML element. That means it will create space outside the border. We can set different sizes for each side of the HTML element(top, right, bottom) if we give different sizes for each side, that will apply first top, right, bottom, left. 

Margin properties can have the following values:

  • Length in cm, px, pt, etc.
  • Width % of the element.
  • Margin calculated by the browser: auto.

Syntax:

body{
  margin: size;
}

We can set margin property in two ways. 

  1. Shorthand property
  2. Individual margin property

In shorthand property we will set all sides values in one line.

Syntax:

body{
  margin: top   right   bottom  left;
}

In individual margin property, we will set for each side values separately.

Syntax:

body{
  margin-top: size;
  margin-right: size;
  margin-bottom: size;
  margin-left: size;
}

margin-top: it will set top margin to the element.

margin-right: it will set right margin to the element.

margin-bottom: it will set bottom margin to the element.

margin-left: it will set left margin to the element.

Note: the margin property allows negative values also.

You can observe the margin in the picture below

Shorthand property

If the margin values has 4 values:

Example:

<html>  
	<head>
		<style>
			div{
				border: 1px solid;
			}
			p{
				border: 1px solid red;
				margin: 70px 90px 150px 70px;
			}
		</style>
	</head>  
	<body>
		<h1>
			 Edupoly Tutorials
		</h1>
		<div> 
			<p> Margin properties </p>
		</div>
	</body>
</html>

Output:

In the above example,

margin-top value is 70px,

margin-right value is 90px,

margin-bottom value is 150px,

margin-left value is 70px.

If the margin property has 3 values:

Example:

<html>  
	<head>
		<style>
			div{
				border: 1px solid;
			}
			p{
				border: 1px solid red;
				margin: 90px 60px 80px;
			}
		</style>
	</head>  
	<body>
		<h1>
			 Edupoly Tutorials
		</h1>
		<div> 
			<p> Margin properties </p>
		</div>
	</body>
</html>

Output:

In the above example,

margin-top value is 90px,

margin-right and left value is 60px,

margin-bottom value is 80px.

 If the margin property has 2 values:

Example:

<html>  
	<head>
		<style>
			div{
				border: 1px solid;
			}
			p{
				border: 1px solid red;
				margin: 100px 150px;
			}
		</style>
	</head>  
	<body>
		<h1>
			 Edupoly Tutorials
		</h1>
		<div> 
			<p> Margin properties </p>
		</div>
	</body>
</html>

Output:

In above example 

margin-top and bottom value is 100px,

margin-right and left value is 150px.

If the margin property has 1 value:

Example:

<html>  
  <head>
      <style>
        p {
             margin: 110px; 
        }
      </style>
  </head>  
  <body>
    <h1>
      Edupoly Tutorials
    </h1>      
    <p> Margin properties </p>  
  </body>  
</html>

Output:

In the above example, margin-top, right, bottom and left values are 110px.