CSS Margin Properties

The following examples demonstrate the various CSS properties you can use to apply margins to any HTML element.

Margins define the space around the element. CSS margins are specified in a similar way to borders - they can be set individually for each side, or all sides at once.

Setting Margins on all Sides

View Output

Setting Margins for Each Side

If you don't want the margin settings to be applied to all four sides, or if you want each side to have different margins applied, you can use the following properties:

Example:

View Output

Shorthand Property

This method uses a shorthand property for setting margin-top, margin-right, margin-bottom, and margin-left in the one place. This method is quicker. It also uses less code than the previous method. Actually, it's the same property that we used in our first example (i.e. the margin property). The only difference is that we apply multiple values against it.

View Output

Variations

You don't need to provide different values for all four sides. You can provide one, two, three, or four values. Here's how it works:

If there is only one value, it applies to all sides. If there are two values, the top and bottom margins are set to the first value and the right and left margins are set to the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively.

In other words:

margin:10px;
  • All four sides have a margin of 10 pixels.
margin:10px 20px;
  • Top and bottom have a margin of 10 pixels.
  • Right and left have a margin of 20 pixels.
margin:10px 20px 30px;
  • Top is 10px
  • Left and right are 20px
  • Bottom is 30px
margin:10px 20px 30px 40px;
  • Top is 10px
  • Right is 20px
  • Bottom is 30px
  • Left is 40px