June 30, 2008 will

A CSS Mnemonic

One of the things that used to annoy me about working with CSS, is that I had a mental block about margin and padding. I could never recall which was which, because the two terms mean pretty much the same thing; an arbitrary space around text. Frankly I think the creators of CSS should have used have called them inner-margin and outer-margin, or inner-padding and outer-padding. I'm sure there is a good reason for using the terms margin and padding (I'm guessing its from typesetting nomenclature), but to me they feel arbitrary and may have well have been called bob and jane.

Fortunately I came up with a mnemonic that made it click. Just remember the phrase 'padded cell'. In a padded cell, the padding goes on the inside. So there you have it, you'll never again forget that the box model is text -> padding -> border -> margin.

Use Markdown for formatting
*Italic* **Bold** `inline code` Links to [Google](http://www.google.com) > This is a quote > ```python import this ```
your comment will be previewed here
gravatar
Kevin GIll

Great tip - simple - thanks

Try out firebug for Firefox. This has a beautiful feature called layout which shows the size of an element, padding, border, margin and offset.

gravatar
Brodie Rao

To make matters more confusing adjacent margins can be collapsed together, while padding cannot. Descendant boxes inside a box with no padding can also have their margins collapsed in such a way that the margin is actually outside of the parent box.

These effects are actually pretty useful with things like paragraphs, but it can be pretty confusing when you're just dealing with divs or trying to style elements that have margins by default.

gravatar
Heather

Do you know the one for the order of values for margin and/or padding?
(If you do, my apologies.)

margin:1px 2px 3px 4px;

"Trouble" Top(1px) , Right(2px), Bottom(3px), Left(4px)

It's the only way I remember.

gravatar
Will

Heather, thats a good one! I've not had much trouble remember the order there. I think of it as a clock hand starting at 12 and moving round to 9.