CSS Margin

As you know the padding property in CSS creates space around the element content. Now you need to know that the margin property in CSS creates a space around the element.

Margin values are set using lengths or percentages and can accept negative values.

Here are the CSS Margin Properties:

We can use margin property for all sides (top, bottom, left, right) at once. For the top side we use margin-top, for bottom margin-bottom, for left side margin-left and for right side margin-right.

Let's see the examples.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        background-color: #1c87c9;
        color: white;
        margin: 25px 10px 15px 20px;
      }
    </style>
  </head>
  <body>
    <p>Paragraph with background-color, color and margin properties.</p>
  </body>
</html>

Let's explain.

We use background-color property for the background of our paragraph, color property for the color of our text and finally we use margin property for the space around element. In this example we just use p element.

Now about margin: 25px 10px 15px 20px. This code means that the margin in the top side must be 25px, in the right side margin 10px, in the bottom side 15px and the left side is 20px.

This property we use when we give the values for all sides. It must look like this in code.

p {
  margin-top: 25px;
  margin-right: 10px;
  margin-bottom: 15px;
  margin-left: 20px;
}

If all sides have the same values, for example all sides are 50px, in css we can write it like this.

p {
  margin: 50px;
}

When we have the same values for the top and the bottom sides (for example 15px) and the same for the left and the right sides (for example 10px), then we can the follow code.

p {
  margin: 15px 10px;
}

This is the same like this one.

p {
  margin-top: 15px;
  margin-right: 10px;
  margin-bottom: 15px;
  margin-left: 10px;
}

When the values for the left and the right sides are the same, for example 15px, the top side is a 5px and the bottom side is 10px, we will write the follow code.

p {
  margin: 5px 15px 10px;
}

This is the same like this one.

p {
  margin-top: 5px;
  margin-right: 15px;
  margin-bottom: 10px;
  margin-left: 15px;
}