CSS Margin Properties

What is Margin?

The CSS margin property defines the space around elements.

Margins are transparent and do not have a background color.

Margins can be set individually for top, right, bottom, and left sides, or all at once.

CSS Margin Properties0

Possible Values

Value Description
auto Let the browser calculate the margin. The result will depend on the browser.
length Defines a fixed margin using units like pixels, pt, em, etc.
% Defines a margin in percentage relative to the containing element.

Remark: Margins can use negative values, allowing for overlapping content.

Margin - Individual Sides

In CSS, you can specify different margins for each side:

margin-top: 100px;
margin-bottom: 100px;
margin-right: 50px;
margin-left: 50px;

Margin - Shorthand Property

To shorten the code, you can use the shorthand margin property to set all margins in one declaration:

margin: 100px 50px;

The margin property can have one to four values:

margin: 25px 50px 75px 100px;

  • Top margin is 25px
  • Right margin is 50px
  • Bottom margin is 75px
  • Left margin is 100px

margin: 25px 50px 75px;

  • Top margin is 25px
  • Left and right margins are 50px
  • Bottom margin is 75px

margin: 25px 50px;
 

  • Top and bottom margins are 25px
  • Left and right margins are 50px

margin: 25px;

  • All four margins are 25px

All CSS Margin Properties

Property Description
margin Shorthand property to set all margin properties in one declaration.
margin-bottom Sets the bottom margin of an element.
margin-left Sets the left margin of an element.
margin-right Sets the right margin of an element.
margin-top Sets the top margin of an element.

Examples

Setting Top Margin with cm Value

This example demonstrates how to set a top margin using the cm value.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Webcode101(webcode101.com)</title> 
<style>
p.ex1 { margin-top: 2cm; }
</style>
</head>
<body>
<p>A paragraph without a specified margin size.</p>
<p class="ex1">A paragraph with a 2cm top margin.</p>
<p>A paragraph without a specified margin size.</p>
</body>
</html>

Setting Bottom Margin with Percentage Value

This example demonstrates how to set a bottom margin using a percentage value relative to the width of the containing element.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Webcode101(webcode101.com)</title> 
<style>
p.bottommargin { margin-bottom: 25%; }
</style>
</head>
<body>
<p>This is a paragraph without a specified margin size.</p>
<p class="bottommargin">This is a paragraph with a specified bottom margin.</p>
<p>This is a paragraph without a specified margin size.</p>
</body>
</html>