freeCodeCamp/guide/english/css/properties/margin-property/index.md

2.7 KiB

title
Margin Property

Margin Property

The margin property is the space around an element, as opposed to padding, which is the space within the element. The margin is transparent and is the outermost element in the Box Model (see diagram below).

Box model diagram

Source: https://css-tricks.com/the-css-box-model/

Setting Margin

There are multiple ways of setting the margin of an element.

The simple way...

  margin: 10px;  

This will put 10 pixels of space completely around the element.

You can also put different amounts of space on each side of an element. For example:

  margin-top: 10px;
  margin-bottom: 15px;
  margin-left: 20px;
  margin-right: 25px;

However, there is a shorthand one can use when defining different sides of an element. It starts at the top and goes clockwise around the element (top, right, bottom, left). For example, the about code would be written in shorhand like this:

  margin: 10px 25px 15px 25px;

Additionally, if the bottom and top margins are the same, and the left and right margins are the same, it can be written like this:

  margin: 10px 20px;

where the top and bottom margins are 10 pixels and the left and right margins are 20 pixels.

Other Property Values

auto - the browser calculates the margins.

initial - set the property to its initial value

inherit - element inherits the margin from its parent element

Measuring Space

Just like there are multiple ways of setting the margin, there are also multiple ways of measuring margin.

px - Measurement in pixels, the standard unit of measurement of screen space.

% - Percentage of the screen. This will make the element shrink and grow with the browser and is one of the recommended units of measurement for responsive web design.

em - size unit relative to the font-size of the current element.

rem - size unit relative to font-size of the root element of the page.

Here is a guide on CSS units.

This quick style guide will help ensure your pull request gets accepted.

More Information: