Difference between margin and padding?

后端 未结 22 1940
广开言路
广开言路 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:16

    One of the key differences between margin and padding is not mentioned in any of the answers: clickability and hover detection

    Increasing the padding increases the effective size of the element. Sometimes I have a smallish icon that I don't want to make visibly larger but the user still needs to interact with that icon. I increase the icon's padding to give it a larger footprint for clicks and hover. Increasing the icon's margin will not have the same effect.

    An answer to another question on this topic gives an example.

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

    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

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

    There is one important difference:

    Margin- is on the outside of the element i.e. one will apply the whitespace shift "after" the element begins. Padding- is on the inside, the other will apply the whitespace "before" the element begins.

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

    Remember these 3 points:

    • The Margin is the extra space around the control.
    • The Padding is extra space inside the control.
    • The Padding of an outer control is the Margin of an inner control.

    Demo Image:(where red box is desire control)

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

    One thing I just noticed but none of above answers mentioned. If I have a dynamically created DOM element which is initialized with empty inner html content, it's a good practice to use margin instead of padding if you don't want this empty element occupy any space except its content is created.

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

    Padding is the space between you content and the border. Where as Margin is the space between the border and the other element.

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