Margin Vs Padding - CSS Properties


CSS provides two properties named margin and padding for keeping space between HTML Box type elements. But why do we have two properties for the same reason? Are they similar?
No. They have a main difference.
Padding - defines space between border and element content
Margin - defines space between border and other outer elements
(Look at the above diagram)

So when elements needs space between them, better to use margins. When text or an inner element needs space between the parent box and itself go for paddings.

Look at this example for visual clarification generated with this code.
<div style="margin:25px; background:#cccccc; border:#000000 2px dashed;">
Text inside element
</div>
<div style="padding:25px; background:#cccccc; border:#000000 2px dashed;">
Text inside element
</div>


Text inside element

Text inside element



In the first <div>, space is set between the border and outside elements but in the second one it is between the boder and text.

Hope this will help.

Check out this stream