Table of Contents

CSS Margins

CSS margins are used to specify space outside an element. You can define the margin for all sides around your element like so:

.box{
    margin: 20px;
}

With a margin of 20px we would get an output that resembles the following:

The CSS Margin Property

The value of the margin can be in pixels px, percent %, or it can be set to auto.

When set to auto, the browser will define the space around the element. This will commonly result in the default margin space of 0.

You can additionally specify the margin for each side of the element, (top, right, bottom, left). Which would look like the following:

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

Additionally this can be written using the short-hand margin property like so:

.box{
    margin: 5px 10px 15px 20px;
}

If the margin property has four values similar to the above example, your element will have the following margin on each side:

margin with 4 values

  • margin-top: 5px;
  • margin-right: 10px;
  • margin-bottom: 15px;
  • margin-left: 20px;

Finally, there is one last way that we can define our elements margin, and that is by passing it 2 values, like so:

.box{
    margin 10px 20px;
}

By specifying 2 values for our margin, our element will use the first value for the top and bottom, and the second value will be used to apply margin to the left and right. So, from the previous code example:

margin with 2 values

  • margin-top: 10px;
  • margin-right: 20px;
  • margin-bottom: 10px;
  • margin-left: 20px;

Let’s summarize the margin property real quick... A margin with 1 value will add that value to all sides. A margin with 2 values will apply the margin to the top-bottom and left-right of your element respectively. And a margin with 4 values will apply the margin to the top, right, bottom, and left side respectively.

It may seem like there are a lot of ways to define your margins. My advice would be to choose which way you like best and which way fits your situation best.

Next we'll talk about CSS padding which is very similar to CSS margins except padding adds space inside the element.