Loading

Margins

  • In CSS margins are used to control space around an HTML element.
  • Margins create space between other elements and the browser window
  • For individual sides(top, bottom, right, left) we can set different sizes of margins
  • Margins are completely transparent and don't have any background color

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: value;
}

 margin properties:

  • margin-top: Indicates the margin on the top of an element.
  • margin-right: Indicates the margin on the right side of an element.
  • margin-bottom: Indicates the margin on the bottom of an element.
  • margin-left: Indicates the margin on the left side of an element.

Note: The margin property allows negative values.

If the margin property has 4 values: 

margin: 40px 100px 120px 80px;
  • top = 40px
  • right = 100px
  • bottom = 120px
  • left = 80px

Example:

margin: 50px 100px 150px 200px;

It identifies that:

top margin value is 50px

right margin value is 100px

bottom margin value is 150px

left margin value is 200px

<!DOCTYPE html> 
<html> 

<head> 
	<style>
		p {
			background-color: pink;
		}

		p.ex {
			margin: 50px 100px 150px 200px;
		}
	</style> 
</head> 

<body> 
	<p>This paragraph is not displayed with specified margin. </p> 
	<p class="ex">This paragraph is displayed with specified margin.</p> 
</body> 

</html>

Output:


 Margins - Percentages:

We can set percentage values for the margins of an element.

Example:

<html>

<head>
	<style>
		h1 {
			margin: 5%;
			background-color: #eee;
		}
	</style>
</head>

<body>
	<div style="width: 600px; border: 1px dotted;">
		<h1>An h1 element with grey background!</h1>
	</div>

	<div style="width: 400px; border: 1px dotted;">
		<h1>An h1 element with grey background!</h1>
	</div>;
</body>

</html>

Output:


 Margins - Inline Elements:

  • Margin values can also be applied to inline elements but top and bottom margins do not have any effect

Example:

<html>
<head>
    <style>
        div {
            border: 1px dotted
        }
        
        strong {
            margin-top: 25px;
            margin-bottom: 50px;
            margin-left: 25px;
            background-color: #eee;
        }
    </style>
</head>
<body>

    <div>
        <p>This text has some strong text <strong>Qupoin</strong> with grey background</p>
    </div>
    
</body>

</html>

Output: