Categories
Web development

CSS margin Property

CSS margin Property

The CSS margin property settles the margins for an element.

The margin creates the space around an element, while the padding creates space within an element.

The CSS margin property is a shorthand property for the following properties:

Syntax:

margin: auto|length;

auto – the browser calculates a margin.

length – defines a fixed margin in px, cm, etc.

The CSS margin property can have from one to four values:

If the margin property has four values:

<!DOCTYPE html>
<html>
<head>
<style>
.ex1 {
  margin: 40px 70px 30px 100px;
}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p class="ex1">This paragraph has a 40px margin for top, a 70px margin for right, a 30px margin for bottom, and a 100px margin for left.</p>
<p>This is a paragraph.</p>

</body>
</html>

Output:

Top margin is 40px, right margin is 70px, bottom margin is 30px and left margin is 100px.

This is a paragraph.

This paragraph has a 40px margin for top, a 70px margin for right, a 30px margin for bottom, and a 100px margin for left.

This is a paragraph.


If the margin property has three values:

<!DOCTYPE html>
<html>
<head>
<style>
.ex2 {
  margin: 45px 80px 60px;
}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p class="ex2">This paragraph has a 45px margin for top, a 80px margin for right and left, and a 60px margin for bottom.</p>
<p>This is a paragraph.</p>

</body>
</html>

Output:

Top margin is 45px, right and left margins are 80px, and bottom margin is 60px:

This is a paragraph.

This paragraph has a 45px margin for top, a 80px margin for right and left, and a 60px margin for bottom.

This is a paragraph.


If the margin property has two values:

<!DOCTYPE html>
<html>
<head>
<style>

.ex3 {
  margin: 30px 10px;
}

</style>
</head>
<body>

<p>This is a paragraph.</p>
<p class="ex3">A paragraph with a top and bottom margin of 30px and a right and left margin of 10px.</p>
<p>This is a paragraph.</p>

</body>
</html>

Output:

Top and bottom margins are 30px, right and left margins are 10px:

This is a paragraph.

A paragraph with a top and bottom margin of 30px and a right and left margin of 10px.

This is a paragraph.


If the margin property has one value:

<!DOCTYPE html>
<html>
<head>
<style>
.ex4 {
  margin: 55px;
}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p class="ex4">This paragraph has a margin of 55px on all four sides.</p>
<p>This is a paragraph.</p>

</body>
</html>

Output:

All four margins are 55px:

This is a paragraph.

This paragraph has a margin of 55px on all four sides.

This is a paragraph.


Enjoy coding!

Read also:

CSS animation Property

CSS border Property