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)?
Margin is said to be the outer space of an element, i.e., the margin is the space outside of the element's border. Padding is said to be the inner space of an element, i.e., the padding is the space inside of the element's border.
In HTML margins work the same way in giving space away from the edge of the page. Borders simply wrap the element. A border can wrap immediately around an element, or it may look further away from an element if more padding has been applied to the element. Padding provides space around the element.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With