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
There are more technical explanations for your question, but if you're looking for a way to think about margin & padding that will help you choose when and how to use them, this might help.
Compare block elements to pictures hanging on a wall:
When deciding between margin & padding, it's a nice rule of thumb to use margin when you're spacing an element in relationship to other things on the wall, and padding when you're adjusting the appearance of the element itself. Margin won't change the size of the element, but padding will typically make the element bigger1.
1 This default box model can be altered with the
box-sizing
attribute.First let's look at what are the differences and what each responsibility is:
So simply Margins are space around elements, while Padding are space around content which are part of the element.
This image from codemancers shows how margin and borders get togther and how border box and content-box make it different.
Also they define each section as below:
CSS Margin, padding and border are Box Model properties.
Total width=content-width + padding + border.
The thing about margins is that you don't need to worry about the element's width.
Like when you give something
{padding: 10px;}
, you'll have to reduce the width of the element by 20px to keep the 'fit' and not disturb other elements around it.So I generally start off by using paddings to get everything '
packed
' and then use margins for minor tweaks.Another thing to be aware of is that paddings are more consistent on different browsers and IE doesn't treat negative margins very well.
The margin clears an area around an element (outside the border), but the padding clears an area around the content (inside the border) of an element.
it means that your element does not know about its outside margins, so if you are developing dynamic web controls, I recommend that to use padding vs margin if you can.
note that some times you have to use margin.
The best I've seen explaining this with examples, diagrams, and even a 'try it yourself' view is here.
The diagram below I think gives an instant visual understanding of the difference.
One thing to keep in mind is standards compliant browsers (IE quirks is an exception) render only the content portion to the given width, so keep track of this in layout calculations. Also note that border box is seeing somewhat of a comeback with Bootstrap 3 supporting it.