Padding vs. Margin

Most beginners get padding and margins mixed up and use them incorrectly. Practices such as using the height to create padding or margins also lead to bugs and inconsistencies. Understanding padding and margins is fundamental to using CSS.

What Is Padding and Margin?

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 <h2> 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:

1    margin: 15px 0 15px 0;
2    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:

1    margin: 15px 0; /*–top and bottom = 15px | right and left = 0 –*/
2    padding: 15px; /*–top, right, bottom and left = 15px –*/

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

1    h2 {
2    background: #f0f0f0;
3    border: 1px solid #ddd;
4    margin: 15px 0;
5    padding: 15px;
6    }


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s