The CSS Margin Properties

The CSS margin properties control the space outside of HTML elements.

1846 views

Edited: 2019-09-11 16:28

Image showing the CSS box model.

The margin refers to the space outside the edge or borders of elements, and it can be controlled with the CSS margin properties.

Note. If you want to control the padding (space) inside an element, use the padding properties instead.

When the margin properties are used, it is usually to create distance to neighboring elements, but they can also be used to move elements closer to each other, usually done by applying a negative margin on an element.

Vertical margins on elements can collapse when they collide. For example, when paragraph elements both have a top and bottom margin, the margin will collapse into the greatest of the two, so a margin of 1em and 2em becomes 2em – not 3em. Horizontal margins never collapses.

Properties

PropertyFunction
marginThe shorthand way to apply margin.
margin-topSpace on the top-edge of an element.
margin-rightSpace on the right-edge of an element.
margin-bottomSpace on the bottom-edge of an element.
margin-leftSpace on the left-edge of an element.

Possible Values

Inherited? NO!

Margin explained

Each element has four margins that can be changed, one for each side: top, right, bottom, and left. These can be set trough the direction orientated properties:

div {
  margin-top: 1em;
  margin-right: 1em;
  margin-bottom: 1em;
  margin-left: 1em;
}

The shorthand way of applying margins is usually the better choice, and will work in the following order: top, right, bottom, left. I.e.

div {
  margin: top right bottom left; /* Note. use a length value in place of these */
}

So, using a length value, the above would actually look like:

div {
  margin: 2em 1em 1em 2em;
}

We can also address all four sides at once:

div {
  margin: 1em; /* All four sides have a margin of 1em */
}

Centering elements

The margin property is often used to center elements by setting the right and left values to auto. For an element to be centered, it will also need to have a width applied. I.e.:

.MyBox {
  width: 50%;
  margin: 0 auto; /* top right bottom left */
}

The above is possible because undefined values in the margin property automatically get copied their opposites. Because we did not define the left value, the right value of auto is being copied to the left value. It is the same for the top and bottom values. The equivalent is to set the margin-left and margin-right properties to auto.

A common way to center a website is to use a div wrapper around the page, and set the margin needed.

.PageWrap {
  width: 93%;
  min-width: 390px;
  max-width: 1900px;
  margin: 0 auto; /* top right bottom left */
}

Tell us what you think: