Margins handle the space between an element and things around it. It is generated outside of the element, so it does not contribute to the size of the element itself like padding does. However, keep in mind that if the size of your element matters in your layout design, you still need to consider how much room both the element and the space around it will take up.
As far as syntax, margin is handled very similarly to padding. Its measurement can be set to pixels or percentage, and you can specify one side of the element using a hyphen and the direction.
Without Margins | |
<div style="width:100px; height:100px; padding:20px; background-color:#555555">
|
With Margins | |
<div style="width:100px; height:100px; padding:20px; background-color:#555555; margin:20px">
|
One nice trick to learn with the margin property right off the bat, is that you can use it to center elements that have set widths. Margin has an available value of auto, where it will automatically calculate the margin. If you apply this value to the left and right margin, the potential margin space on either side of your element will be evenly split between the two, thus, centering your element.
<div style="width:300px; height:100px; |
Margin does have a peculiar behavior that can be confusing without an explanation. Say you have one element with a margin-right set to 20px, and a second element next to it with a margin-left of 20px. These values will add together and there will be a total of 40px of space between the two elements. That’s nothing unusual.
However, when it comes to margin above and below elements, things can get a little weird. Any elements that adjust their height based on the content inside them are known as block elements. These include paragraphs, headers and divs--all elements that, by default, go the full width of the screen and start on their own line. When it comes to block elements, competing margins above and below each other will collapse. For example, if you have one paragraph with a margin-bottom of 20px above another paragraph that has a margin-top of 20px, there will be 20px of space between them, not 40px.
Why does this happen? It comes back to block elements having height that adjusts automatically based on their content. Plus, block elements like paragraphs and headers have default margins above and below themselves to put space between blocks of text. If this collapsing behavior didn’t happen, there'd be a lot of extra space between paragraphs.
The top and bottom margins of competing block elements will always go with the higher value. So if you need a margin of 40px between two paragraphs, don’t set each one to a value of 20px. Set just one of them to 40px.
<p style="margin-bottom:20px">Paragraph 1</p> |
Paragraph 1 Paragraph 2 |
<p style="margin-bottom:40px">Paragraph 1</p> |
Paragraph 1 Paragraph 2 |