CSS: padding vs margin

What is padding in CSS? And margin? What's the difference?

I know that the subject is very basic, but recently I noticed that people tend to confuse them, use them together (which is ok) or switch from one to the other without knowing why. Sometimes using them  - especially with transparent elements - we might not notice the difference between the two properties.

The definitions
Let's start from the beginning.
Margin: it defines the distance between the element and other elements. It's like a surrounding space and determines what's the measure of that space. The margin is outside the object and it is always transparent.
Padding: it defines the distance from the border of the element and its content. The padding is inside the object and it takes its background color.


Both properties can be used to define the top, bottom, left and right margin and/or padding independently.

For example:
.class {
margin-top: 10px;
margin-bottom: 5px;
margin-left: 20px;
margin-right: 1px;
}
Otherwise, we can use a shorthand version. In this case, the values are - in order - top, right, bottom, left. Those values can be combined together.
Examples:
.class {
margin: 10px 1px 5px 20px;
}
Which is: top=10px, right=1px, bottom=5px, left=20px.
.class {
margin: 10px 20px 5px;
}
Which is: top=10px, right=left=20px, bottom=5px.
.class {
margin: 10px 20px;
}
Which is: top=bottom=10px, left=right=20px.

All the above applies to padding as well.

What values can we use?
For margin we can set value as:
auto: the browser sets the margins;
value: in pixels, em, pt or percentage.
For padding:
value: in pixels, em, pt or percentage.

The effect
Let's try and see the effect. Consider this example:
.box
{
margin: 10px;
}
The result:

The text

I just added some borders to better explain the example."The text" is inside a container (with a class set to "box"), while I created a parent container so that we can see the effect of the margin property. The distance between the red box and the black box is 10px (the margin).

Let's see padding:
.box
{
padding: 10px;
}
The result:

The text

which is clearly different. The padding is defining the space from the text and its container: between "The text" and the black box.

Together?

The text

Just a side note. In this article to render the effect of margin and padding I had to use tables. That is because Blogger won't let me use styles the proper way. So, please, do not get confused if you try and see the code behind this article.

Hope you like the post and let me know what you think.