Difference between margin and padding?

What exactly is the difference between margin and padding in CSS? It really doesn't seem to serve much purpose. Could you give me an example of where the differences lie (and why it is important to know the difference)?


Solution 1:

padding is the space between the content and the border, whereas margin is the space outside the border. Here's an image I found from a quick Google search, that illustrates this idea.

enter image description here

Solution 2:

One key thing that is missing in the answers here:

Top/Bottom margins are collapsible.

So if you have a 20px margin at the bottom of an element and a 30px margin at the top of the next element, the margin between the two elements will be 30px rather than 50px. This does not apply to left/right margin or padding.

Solution 3:

Margin is applied to the outside of your element hence affecting how far your element is away from other elements.


Padding is applied to the inside of your element hence affecting how far your element's content is away from the border.

Also, using margin will not affect your element's dimensions whereas padding will make your elements dimensions (set height + padding) so for example if you have a 100x100px div with a 5px padding, your div will actually be 105x105px

Solution 4:

Remember these 3 points:

  • The Margin is the extra space around the control.
  • The Padding is extra space inside the control.
  • The Padding of an outer control is the Margin of an inner control.

Demo Image:(where red box is desire control) enter image description here