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
It's good to know the differences between
margin
andpadding
. Here are some differences:Margin is outer space of an element, while padding is inner space of an element.
Margin is the space outside the border of an element, while padding is the space inside the border of it.
Margin accepts the value of auto:
margin: auto
, but you can't set padding to auto.Margin can be set to any number, but padding must be non-negative.
When you style an element, padding will be affected also (e.g. background color), but not margin.
I always use this principle:
This is the box model from the inspect element feature in Firefox. It works like an onion:
So bigger margins will make more space around the box that contains your content.
Larger padding will increase the space between your content and the box of which it is inside.
Neither of them will increase or decrease the size of the box if it is set to a specific value.
From https://www.w3schools.com/css/css_boxmodel.asp
Live example (play around by changing the values): https://www.w3schools.com/css/tryit.asp?filename=trycss_boxmodel
Advanced Margin versus Padding Explained
It is inappropriate to use
padding
to space content in an element; you must utilizemargin
on the child element instead. Older browsers such as Internet Explorer misinterpreted the box model except when it came to usingmargin
which works perfectly in Internet Explorer 4.There are two exceptions when using
padding
is appropriate to use:It is applied to an inline element which can not contain any child elements such as an input element.
You are compensating for a highly miscellaneous browser bug which a vendor *cough* Mozilla *cough* refuses to fix and are certain (to the degree that you hold regular exchanges with W3C and WHATWG editors) that you must have a working solution and this solution will not effect the styling of anything other then the bug you are compensating for.
When you have a 100% width element with
padding: 50px;
you effectively getwidth: calc(100% + 100px);
. Sincemargin
is not added to thewidth
it will not cause unexpected layout problems when you usemargin
onchild elements
instead ofpadding
directly on the element.So if you're not doing one of those two things do not add padding to the element but to it's direct child/children element(s) to ensure you're going to get the expected behavior in all browsers.
One thing to note is when auto collapsing margins annoy you (and you are not using background colours on your elements), something it's just easier to use padding.