Understanding CSS box model properly

I’ve noticed a lot of developers are unsure of how the box model concept works with respect to how rectangles are created for elements laid out on the DOM tree. Although this document explains it pretty well, I built a small example which I feel also demonstrates the core concept reasonably well.

http://jsfiddle.net/thxzc/1/

4 main concepts to properly understand the box model:

  1. Content: The actual content area with a width and height specified to it.
  2. Padding: Clears space inside the rectangle created for the content rectangle above. This padding also assumes he background color of the content area.
  3. Margin: Clears space OUTSIDE the rectangle created for the content rectangle above.
  4. Border: The border wraps around the content area/rectangle + the padding. It may or may not have its own color.

The actual size of the node includes the padding and the border. So if the width of a node is 200px, and it has a 10px padding and 1px border around it. Its real width is 222px(width + paddingLeft + paddingRight + borderLeft + borderRight).

Execute the example again and you will see how the height and width of the content area are computed: http://jsfiddle.net/thxzc/1/

Advertisements