The CSS background-color property makes things look nice and pretty. But, they don’t play well with margin in a block-based layout where the body tag’s background-color is different from your content’s background-color, especially when you’re using a liquid height layout.
Let’s say you’re stacking three divs on top of each other for a nice stack. That middle div has a background-color. Now, adding a block-level element with built-in margin (like a p or h1) to that middle div will cause a big huge band of color where the element’s enforced margin pushes down the block beneath it. (Is it a bug? Nope. Just doing what it’s supposed to.)
How in the heck to you get rid of that band of color? Simple: add something below that block-level or margin-enforcing element, or add padding to the block-level element’s container. The margin is enforced on the item below, which gets pushed down, but also stretches the container’s height, keeping the color in tact. Ditto with the padding: the padding forces a height on the container, keeping the background in tact and delightful.
Feel like playing with margins? Give a margin-bottom of 0 to that problem element. Or, give a margin-top of a negative value to the block that’s being pushed down (it’s roughly the line-height or specified font-size that’s in effect on the container).
There’s four simple, friendly ways to make margins play nice. The third is probably the cleaneast; the fourth the dirtiest (especially if another developer doesn’t see that negative margin, and wonders why blocks are overlapping after he’s made a change to the code). But, all do the job.
technorati tags:css, background-color, margin, html, liquid layouts