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 examp
One of the key differences between margin and padding is not mentioned in any of the answers: clickability and hover detection
Increasing the padding increases the effective size of the element. Sometimes I have a smallish icon that I don't want to make visibly larger but the user still needs to interact with that icon. I increase the icon's padding to give it a larger footprint for clicks and hover. Increasing the icon's margin will not have the same effect.
An answer to another question on this topic gives an example.
Margin is applied to the outside of you element hence effecting how far your element is away from other elements.
Padding is applied to the inside of your element hence effecting 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 5 px padding, your div will actually be 105x105px
There is one important difference:
Margin- is on the outside of the element i.e. one will apply the whitespace shift "after" the element begins. Padding- is on the inside, the other will apply the whitespace "before" the element begins.
Remember these 3 points:
Demo Image:(where red box is desire control)
One thing I just noticed but none of above answers mentioned. If I have a dynamically created DOM element which is initialized with empty inner html content, it's a good practice to use margin instead of padding if you don't want this empty element occupy any space except its content is created.
Padding is the space between you content and the border. Where as Margin is the space between the border and the other element.