Originally posted on 10/19/08 at http://likesalmon.wordpress.com
The other day I was laying out a wordpress driven site in css and realized that I didn’t actually understand how the “width” property works. This was extremely embarrassing to admit to myself, because it means I’ve been flubbing and cheating my way through the layout of every website I’ve developed so far. Its one the things that fell through the cracks because of limited time or lack of will. So I did a little testing and it turns out the width property works in the most obvious way possible, with one exception. Here are the results of my test:
All of the following boxes are div elements set to width: 200px; height: 200px and background-color: #ccc. I use lots of shorthand, so you’ll want to review that or this won’t make much sense. I performed this test in Firefox 3 so I trust that this behavior is the standard.
The following code was removed because it was breaking my layout — ed.
border: 10x;. Notice how the inner box is still 200px by 200px. The border has been added to the outside. The total dimensions of the div are now 220px by 220px.margin: 40px. The space it now takes up is 280px by 280px. Margins appear to behave exactly like borders, except they are always transparent.padding: 10px;. Notice how this expanded the box 10px on each side, for a total height and width change of 20px. This is the one unexpected behavior I encountered: I figured it would constrain the contents of the box instead of expanding the box itself.padding: 10px;. The difference is that this one is nested inside a div with width: 200px; height: 200px;. Unless the overflow: hidden; property is set, this makes no difference at all. The box still expands to 220px by 220px and overflows the container div.<p> element that follows this div so they don’t overlap.In conclusion, if you’re designing a site that is 800px wide with an 8px border, you would subtract the width of the border from the width of the container element like so: #container { width: 792px; border: 8px solid #ccc; }. The #container element stays at 800px and everyone is happy.