Working with CSS margins

The CSS margin property is useful to set spaces around any element. We can set the margin of an element for all the 4 side altogether or individually.

There are four CSS properties available to set margin individually for particular side.

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

The margin values we can provide in px, rem, pt, %, cm, auto, inherit etc.

.element {
     margin-top: 50px;
     margin-right: 10px;
     margin-bottom: 30px;
     margin-left: 40px;
  }

To set the margin for all the 4 side together, we can use the shorthand margin property of CSS. The margin property can take either 4 values or 3 values or 2 values or 1 value separated by spaces.

If the margin has 4 values, that means the 1st value is margin-top, 2nd is margin-right, 3rd is margin-bottom and 4th is margin-left.

margin: 50px 10px 30px 40px;

This is same as

margin-top: 50px;
margin-right: 10px;
margin-bottom: 30px;
margin-left: 40px;

If the margin has three values, that means the 1st value is margin-top, 2nd value is both margin-right and margin-left, 3rd value is.

margin: 50px 10px 30px;

This is same as

  margin-top: 50px;
  margin-right: 10px;
  margin-bottom: 30px;
  margin-left: 10px;

If the margin has two values, that means the 1st value is both margin-top and margin-bottom, 2nd value is both margin-right and margin-left.

margin: 50px 10px;

This is same as

  margin-top: 50px;
  margin-right: 10px;
  margin-bottom: 50px;
  margin-left: 10px;

If the margin has only one value then that value is same for all side margins.

margin: 50px;

This is same as

  margin-top: 50px;
  margin-right: 50px;
  margin-bottom: 50px;
  margin-left: 50px;

Checkout next: Working with CSS Padding

Leave a Reply

Your email address will not be published. Required fields are marked *