When to use margin vs padding in CSS -
While writing CSS, there is a specific rule or guideline that should be used to decide margins and
padding
?
TL; DR: By default I use margin everywhere, except that I have a border or background and want to increase the space inside that visible box.
The biggest difference between me and pading margins is that the vertical margin does not automatically collapse, and padding. Consider two elements above each other with padding 1 AM. This padding is considered to be part of the element, and it is always preserved. Then you will end up with the content of the first element, after which the padding of the first element, after the second padding, after the content of the second element Thus the content of two elements will be separated by 2em.
Now replace that padding with 1em margin. Margin is considered outside the element, and margin of adjacent objects will overlap. So in this example, you will end up with the content of the first element, after which the contents of the second element will be 1em of the combined margin. Therefore the content of two elements is only 1em different
This can be really useful when you know that you want to say 1em of space around the element, even then what is this element.
The other two big difference is that the padding is included in the click area and background color / image, but the margin is not
Comments
Post a Comment