When writing CSS, is there a particular rule or guideline that should be used in deciding when to use margin
and when to use padding
?
相关问题
- Adding a timeout to a render function in ReactJS
-
Why does the box-shadow property not apply to a
- Add animation to jQuery function Interval
- jQuery hover to slide?
- Issue with star rating css
Margin is outside the box and padding is inside the box
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 the 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 only1em
apart.This can be really useful when you know that you want to say
1em
of spacing around an element, regardless of what element it is next to.The other two big differences are that padding is included in the click region and background color/image, but not the margin.
Margin
Margin is usually used to create a space between the element itself and its surround.
for example I use it when I'm building a navbar to make it sticks to the edges of the screen and for no white gap.
Padding
I usually use when I've an element inside a border,
<div>
or something similar, and I want to decrease its size but at the time I want to keep the distance or the margin between the other elements around it.So briefly, it's situational; it depends on what you are trying to do.
Margin is on the outside of block elements while padding is on the inside.
Here is some HTML that demonstrates how
padding
andmargin
affect clickability, and background filling. An object receives clicks to its padding, but clicks on an objects margin'd area go to its parent.MARGIN vs PADDING :
Margin is used in an element to create distance between that element and other elements of page. Where padding is used to create distance between content and border of an element.
Margin is not part of an element where padding is part of element.
Please refer below image extracted from Margin Vs Padding - CSS Properties