CSS Margins & Padding

Margins and padding are identical in that they both add whitespace to an area, but unique in that their areas cannot overlap. Padding is applied to the area between an element's content and its border, while margins are applied to the area outside of the border, between the border and other elements. This is described in more detail using the box model that we discussed previously.

CSS Margins

There are five margin properties available. Each property can accept three different types of values. These values are:

Value Purpose Example
Auto Allows the Browser to Determine the Margin or Lack of Margin margin: auto;
Length Sets a Fixed Margin In Pixels (px), Points (pt) or Font-Size (em) margin: 5em;
Percent (%) Sets the Margin As A Percentage of the Containing Element margin: 5%;

Four of the five margin properties are self-explanatory as to which margin size they are setting:

p {
  margin-top: 25px;
  margin-right: 25px;
  margin-bottom: 25px;
  margin-left: 25px;
}

The fifth margin property is a short-hand of the other four. It can contain 1-4 values at one time.

margin: 5px;   /* Sets All 4 Margins to the Same Value */
margin: 5px 10px;   /* Top & Bottom Are 5px, Right & Left Are 10px */
margin: 5px 10px 15px;   /* Top Is 5px, Right & Left Are 10px, Bottom Is 15px*/
margin: 5px 10px 15px 20px;   /* Sets Top, Right, Bottom & Left */

CSS Padding

The properties and values for CSS padding are identical to margins, with the exception that the value of "auto" does not exist, and the word "margin" is replaced with "padding".

p {
  padding-top: 25%;
  padding-right: 25%;
  padding-bottom: 25%;
  padding-left: 25%;
}

p { padding: 5px; }   /* Sets All 4 Sides to the Same Value */
p { padding: 5px 10px; }   /* Top & Bottom Are 5px, Right & Left Are 10px */
p { padding: 5px 10px 15px; }   /* Top Is 5, Right/Left Are 10, Bottom Is 15 */
p { padding: 5px 10px 15px 20px; }   /* Sets Top, Right, Bottom & Left */