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 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.
Basically, the difference between padding and margin come in terms of the background. Padding will decide the space between content, while margin decide the outside edge of elements!
Try putting a background color on a block div with width and height. You'll see that padding increases the size of the element, whereas margin just moves it within the flow of the document.
Margin is specifically for shifting the element around.
margin = space around (outside) the element from border outwards.
padding = space around (inside) the element from text to border.
see here: http://jsfiddle.net/robx/GaMpq/
It is good to know about the differences between margin
and padding
. As I know:
auto
value to margin. However, it's not allowed for padding. See this.
margin: auto
to center a block element inside its parent horizontally. Also, it's possible to center an element inside a flexbox vertically or horizontally or both, by setting margin to auto. See this.
background-color
property to black, its inner space (i.e. padding) will be black, but not its outer space (i.e. margin).
Margin is space outside the box; padding is space inside the box. It's hard to see the difference with a white fill, but with a colored fill you can see it fine.