When to use margin vs padding in CSS

在编写CSS时,应该在决定何时使用margin以及何时使用padding时使用特定的规则或准则?


TL;DR: By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.

To me the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't. Consider two elements one above the other each with padding of 1em. This padding is considered to be part of the element, and is always preserved. So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element. Thus content of the two elements will end up being 2em apart.

Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap. So in this example you will end up with the content of the first element followed by 1em of combined margin followed by the content of the second element. So the content of the two elements is only 1em apart.

This can be really useful when you know that you want say 1em of spacing around an element, regardless of what element it is next to.

The other two big differences is that padding is included in the click region and background color/image, but not the margin.


Margin is on the outside of block elements while padding is on the inside.

  • Use margin to separate the block from things outside it
  • Use padding to move the contents away from the edges of the block.

  • The best I've seen explaining this with examples, diagrams, and even a 'try it yourself' view is here.

    The diagram below I think gives an instant visual understanding of the difference.

    One thing to keep in mind is standards compliant browsers (IE quirks is an exception) render only the content portion to the given width, so keep track of this in layout calculations. Also note that border box is seeing somewhat of a comeback with Bootstrap 3 supporting it.

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

    上一篇: 我该如何解决android.os.NetworkOnMainThreadException?

    下一篇: 何时在CSS中使用margin和padding