The Data Asylum

Programming, Databases and People

Css Margin and Padding Shorthand

Css provides short hand properties for margin and padding which let you define multiple properties at once. For example:-

1
2
3
4
5
6
7
8
9
10
p {
  /* Shorthand */
  margin: 20px 5px 5px 10px;

  /* The Long Equivalent */
  margin-top: 20px;
  margin-right: 5px;
  margin-bottom: 5px;
  margin-left: 10px;
}

There are four variations of the shorthand property. You can specify 1, 2, 3 or 4 values, which are applied to the top, bottom, left and right margins. The problem that I had was trying to determine which value is applied to which side, especially if there are 2 or 3 values. There is an easy way to remember however.

Start at the top and go clockwise. If you run out of values, use the value already set for that axis.

So for example…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
p {
  margin: 20px   5px      5px       10px;
  /*      top -> right -> bottom -> left    */

  margin: 20px   5px      5px;
  /*      top -> right -> bottom
                 left                       */

  margin: 20px   5px;
  /*      top -> right
          bottom left                       */

  /* the expection is for a single value. This applies to all sides. */
  margin: 20px;
  /*      all (top, right, bottom and left) */
}

Comments