Collapsing margins
Let’s say you tried the following HTML/CSS:
<div style="background: #cfc;">
<p style="border: 1px solid black; margin: 1em;">Heya!</p>
</div>
It would look like this:
Heya!
You probably expected it to look like this:
Heya!
The cause of this confusion is called collapsing margins. It only happens to vertical margins, which is why you can you can still see the gray margins outside the left and right border of the paragraph in the first demonstration. According to the CSS 2.1 specs, section 10.6.3:
If [a block-level non-replaced element in normal flow when 'overflow' computes to 'visible'] has block-level children, the height is the distance between the top border-edge of the topmost block-level child box that doesn’t have margins collapsed through it and the bottom border-edge of the bottommost block-level child box that doesn’t have margins collapsed through it. However, if the element has a non-zero top padding and/or top border, or is the root element, then the content starts at the top margin edge of the topmost child. (The first case expresses the fact that the top and bottom margins of the element collapse with those of the topmost and bottommost children, while in the second case the presence of the padding/border prevents the top margins from collapsing.) Similarly, if the element has a non-zero bottom padding and/or bottom border, then the content ends at the bottom margin edge of the bottommost child.
Note the mention of ‘a non-zero top padding and/or top border’. This means that setting either will stop margins from collapsing. In the second example, I added 1 pixel of padding to the DIV for the desired effect. Thanks to Minz Meyer for the solution.