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)?


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.


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

链接地址: http://www.djcxy.com/p/5016.html

上一篇: android.os.NetworkOnMainThreadException与android 4.2

下一篇: 边距和填充之间的区别?