Difference between margin and padding?

后端 未结 22 1950
广开言路
广开言路 2020-11-22 12:58

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

相关标签:
22条回答
  • 2020-11-22 13:05

    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.

    0 讨论(0)
  • 2020-11-22 13:05

    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!

    0 讨论(0)
  • 2020-11-22 13:06

    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.

    0 讨论(0)
  • 2020-11-22 13:07

    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/

    0 讨论(0)
  • 2020-11-22 13:07

    It is good to know about the differences between margin and padding. As I know:

    • Margin is the outer space of an element, while padding is the inner space of an element. In other words, margin is the space outside of an element's border, while padding is the space inside of its border.
    • You can set auto value to margin. However, it's not allowed for padding. See this.
      Note: Use 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.
    • Margin can be any float number, but padding must not be negative.
    • When you style an element, padding will be styled also; but not margin. Margin gets the parent element's style. For example, when you set the background-color property to black, its inner space (i.e. padding) will be black, but not its outer space (i.e. margin).
    0 讨论(0)
  • 2020-11-22 13:07

    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.

    0 讨论(0)
提交回复
热议问题