CSS Margin

CSS

In this tutorial we will learn about margin.

In the above image the area colored in orange is the margin for the element highlighted in blue.

margin

It is a space around an element that separates it from other elements.

We can set the value of margin in length, percentage, auto, and inherit.

When margin is set as length we use px, mm, cm etc.

In the following code we have set the margin to 10px.

div {
	margin : 10px;
}

When margin is set to 0 then we don't use the px unit.

div {
	margin : 0;
}

If the margin is set to auto then the browser calculates the margin for the element.

To inherit the margin from the parent we use the inherit value for the margin.

Margin value is not inherited from the parent element by default.

We can also use negative value for margin.

Margin all 4 sides

There are 4 sides for an element and when we set the margin property we are setting it for all the 4 sides.

To get better control we can set margin separately for each sides using the following properties.

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

In the following example we have set the margin of each sides of the div element having class container.

div.container {
	margin-top : 30px;
	margin-right : 15px;
	margin-bottom : 10px;
	margin-left : 5%;
}

margin shorthand

We can set the margin of each sides using the following shorthands.

div {
	margin : 30px 15px 10px 5%;
}

The above rule will set:

  • margin-top = 30px
  • margin-right = 15px
  • margin-bottom = 10px
  • margin-left = 5%
div {
	margin : 30px 15px 10px;
}

The above rule will set:

  • margin-top = 30px
  • margin-right = 15px
  • margin-bottom = 10px
  • margin-left = 15px
div {
	margin : 30px 15px;
}

The above rule will set:

  • margin-top = 30px
  • margin-right = 15px
  • margin-bottom = 30px
  • margin-left = 15px
div {
	margin : 30px;
}

The above rule will set:

  • margin-top = 30px
  • margin-right = 30px
  • margin-bottom = 30px
  • margin-left = 30px

Inherit margin

In the following example the child element is inheriting the margin from the parent element.

div.container {
	margin : 15px;
}

div.container p {
	margin : inherit;
}

Centering using auto

To center an element we can set value of the left and right margin property of the element to auto and also set the width property. If width is not set then the element will take up the entire width of its container.

In the following example we have centered the div element having class center-container.

div.center-container {
	width : 300px;
	margin : 15px auto;
}

The above rule will set:

  • width = 300px
  • margin-top = 15px
  • margin-right = auto
  • margin-bottom = 15px
  • margin-left = auto