crus4

logo

CSS Margin


The CSS margin property is used to create space around an HTML element, outside the defined borders.

With CSS, we have full control over the margins. We can setup the margin for each side of an element (top, right, bottom and left) by using the properties:

These margin properties can have the following values:

In an example below let’s write a code where we set different margins for all four sides of an element.

Example

<!DOCTYPE html>
<html>
<head>
<style>
p {
  border: 1px solid green;
  margin-top: 80px;
  margin-bottom: 80px;
  margin-right: 40px;
  margin-left: 40px;
  background-color: lightblue;
}
</style>
</head>
<body>
<h2>Using individual margin properties</h2>
<p>This p element with a lightgrey background color, has a top margin of 80px, a right margin of 40px, a bottom margin of 80px, and a left margin of 40px.</p>
</body>
</html>

margin– shorthand

By writing the code like we write in an above example, can makes a code long and difficult to read. Because we have write all four margin properties (top, bottom, right, left) in a separate line.

So, in order to shorten the code and make it easy to read, we can specify all the margin properties in a single line.

p {
  margin: 80px 800px 40px 40px;
}

Now let’s put the same code in a below example to see how it works.

Example

<!DOCTYPE html>
<html>
<head>
<style>
p {
  border: 1px solid green;
  margin: 80px 80px 40px 40px;
  background-color: lightblue;
}
</style>
</head>
<body>
<h2>Let's put all four margin properties in a single line.</h2>
<p>Here we have put the all four margin properties in a single line and you see our code works perfectly.</p>
</body>
</html>

If the margin property has 3 value, like this:

p {
  margin: 40px 25px 60px;
}

In that case, top margin is 40px, right and left margins are 25px and bottom margin is 60px.

If the margin property has 2 value, like this:

p {
  margin: 40px 60px;
}

In that case, top and bottom margins are 40px and right and left margins are 60px.

If the margin property has only 1 value, like this:

p {
  margin: 40px;
}

In that case, all four margins are 40px.

The auto Value

We can also set the margin property to auto, to horizontally center the element within its container.

Then the element takes up the specified width, and the remaining space will be split equally between the left and right margins.

In an example below let’s write a code and set the margin property to auto, and see the results.

Example

<!DOCTYPE html>
<html>
<head>
<style>
p {
  width: 300px;
  margin: auto;
  border: 1px solid red;
  background-color:lightgrey;
}
</style>
</head>
<body>
<h2>Set the margin property to auto.</h2>
<p>This paragraph will be horizontally centered because it has margin auto.</p>
<hr>
</body>
</html>
CSS Margin