Padding is the inner space of an element, and margin is the outer space of an element.

The difference becomes clear once you apply backgrounds and borders to an element. Unlike padding, margins are not covered by either the background or border because they are the space outside of the actual element.

Take a look at the visual below:


Margin and padding values are set clockwise, starting from the top.

Practical example: Here is an  

heading between two paragraphs. As you can see, the margin creates white space between the paragraphs, and the padding (where you see the background gray color) gives it some breathing room.


Margin and Padding Values

In the above example of the heading, the values for the margin and padding would be:

[code lang=”css”]
margin: 15px 0 15px 0;
padding: 15px 15px 15px 15px;

To optimize this line of code further, we use an optimization technique called “shorthand,” which cuts down on repetitive code. Applying the shorthand technique would slim the code down to this:

[code lang=”css”]
margin: 15px 0; /*–top and bottom = 15px | right and left = 0 –*/
padding: 15px; /*–top, right, bottom and left = 15px –*/

The margin property can have from one to four values (also applies to padding).

  • margin:25px 50px 75px 100px;
    • top margin is 25px
    • right margin is 50px
    • bottom margin is 75px
    • left margin is 100px
  • margin:25px 50px 75px;
    • top margin is 25px
    • right and left margins are 50px
    • bottom margin is 75px
  • margin:25px 50px;

    • top and bottom margins are 25px
    • right and left margins are 50px
  • margin:25px;

    • all four margins are 25px

Here is what the complete CSS would look like for this heading:

[code lang=”css”]
h2 {
background: #f0f0f0;
border: 1px solid #ddd;
margin: 15px 0;
padding: 15px;

Quick Tip

Keep in mind that padding adds to the total width of your element. For example, if you had specified that the element should be 100 pixels wide, and you had a left and right padding of 10 pixels, then you would end up with 120 pixels in total.

100px (content) + 10px (left padding) + 10px (right padding) = 120px (total width of element)

Margin, however, expands the box model but does not directly affect the element itself. This tip is especially handy when lining up columns in a layout!

(Visited 2 times, 1 visits today)