Marty Trujillo

The Box Model

In the Spring of 2011 I was doing a phone interview with a very nice guy from a fortune 100 company. The interview went very well with a few exceptions. He asked me to explain the box model and to explain how the box model varies from browser to browser.

The bad news is that I didn't have a clue. I have heard the term before, but that is all. The good news is that the box model is super simple and knowledge of it and the various work arounds will make my life much MUCH easier in the future.

The W3C has a draft specification describing the box model. The box model is a series of squares and accoring that that specification their are four squares within each other. The innermost square is the content. The content is surrounded by the padding. The padding is surrounded by the border. The border is surrounded by the margin.

Margin
Border
Padding
Content

That's basically it. All divs, spans, paragraphs... in HTML are basically squares. The inside square is the content. The next square is the paddings. Next is the border. Finally, we have the margin.

According to the W3C specification when all when a box's width is set the width is from the left side of the content to the right side of the content. I am not sure when the specification was written, but there is a problem some older browsers (IE6 and below) weren't implemented that way. They were implemented so that the width is from the left border to the right border. You can read more about the IE issue.

So why is this a problem? So the UI may vary a little bit from browser to browser. I have struggled with this problem many times. The reason is that designers often deliver designs with very tight tolerances. Many times you can set the HTML and CSS to display perfectly in FF and IE8 only to find that divs floating to the right on FF are slipping under in IE6... designers hate that. This is a pretty big deal because many times the developer has to slide something into a very narrow content pane. I wish would have known about this years ago.


Valid HTML 4.01 Transitional