CSS margin – 2 ways to use margin with 4 examples

The margin property

The margin and padding properties add spaces in the specified HTML elements. The difference between the margin and padding is that the margin property adds space between different element’s borders. While padding adds space between the content and border within the specified element.

>>See a margin property by single declaration example

>>An example of setting margins indivdually

This chapter explains about margin CSS property. You can use the shorthand of this property to specify spaces for all directions i.e. top, bottom, right and left. On the other hand, you can use each direction independently to specify space in CSS margin property.

The example below shows how you can use margin in CSS by both ways.

Add margins by the single declaration

You can use CSS margin property shorthand to specify margins in all directions. If only one value is given in the margin property it will be applied to all four directions, as shown below.

Experience this example online


Add margins with four values example

This example uses four values to define the margins in HTML element.

This is the sequence if you specify four values in the margin property:

  • The first value is for CSS margin top.
  • The second is right.
  • Third is the bottom.
  • Fourth defines the left margin.
Experience this example online


A margin example with two values

If you specify only two values then the first value will define margin for top and bottom and the second value will define margin for the left and right.

Experience this example online


Using margins individually: margin-top and margin-left properties example

Instead of using the shorthand margin CSS property you can use the individual property for each direction. The example below shows how to use the margin-top and margin-left properties to define spaces.

Experience this example online


Similarly, you can use CSS margin-right and margin-bottom properties to define margin of the elements.

Also see: CSS Padding

Was this article helpful?

Related Articles

Leave A Comment?