CSS Margin

CSS margin specifies the space around an element outside the border. By using CSS margin properties you can easily use space outside the border of a element. You can also use the negative values in the margin properties.
Here are the CSS margin proerties:

  • margin-top - Specifies the margin at the top of an element.
  • margin-bottom - Specifies the margin at the bottom of an element.
  • margin-left - Specifies the margin at the left of an element.
  • margin-right - Specifies the margin at the right of an element.
  • margin - It is a shorthand way to declare the other margin properties.

Values of margin Properties

  1. length - The margin can be defined by px, cm, pt etc.
  2. percentage(%) - The margin can be defined by percentage.
  3. auto - The margin will be defined by the browser.
  4. inherit - The margin will be inherited by the parent element.

Example:

h1 {
  margin-top: 50px;

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

Run Example

The margin Property

It is a shorthand property. You can define all the margin proerties in one line by using margin property. the are several way to use the margin property.

If the margin property contains four values. Then the order will be:

  1. margin-top
  2. margin-right
  3. margin-bottom
  4. margin-left

Example:

h1 {
  margin: 50px 30px 60px 20px;
}

Run Example

In the example:

  • margin-top: 50px
  • margin-right: 30px
  • margin-bottom: 60px
  • margin-left: 20px

If the margin property contains three values. Then the order will be:

  1. margin-top
  2. margin-right and margin-left
  3. margin-bottom

Example:

h1 {
  margin: 50px 30px 60px;
}

Run Example

In the example:

  • margin-top: 50px
  • margin-right, margin-left: 30px
  • margin-bottom: 60px

If the margin property contains two values. Then the order will be:

  1. margin-top and margin-bottom
  2. margin-right and margin-left

Example:

h1 {
  margin: 100px 300px;
}

Run Example

In the example:

  • margin-top, margin-bottom: 100px
  • margin-right, margin-left: 300px

If the margin property contains one value then all four margins get the same value.

Example:

h1 {
  margin: 100px;
}

Run Example

In the example:

  • margin-top, margin-bottom, margin-right, margin-left: 100px