Every element on a web page generates a rectangular box. This is often referred to as the box model. The web standards body, the W3C, calls it a visual formatting model. This article offers tips on understanding the CSS box model.
Each element has a box around it. Each box has a content area and optional surrounding padding, border and margin areas.
2
Padding and margin are transparent, allowing the background or background image to show through.
3
Values for padding, border and margin can be defined collectively for each property, or individually for each property on the box top, right, bottom and left.
4
The W3C specifications define the box width as "the sum of the left and right margins, border, padding, and the content width." The box height is defined as "the sum of the top and bottom margins, border, padding and the content height."
Study this example:
div {
width: 100px;
padding: 10px;
border: 5px;
margin: 10px;
}
5
Find width for the example in Step 4 by adding it all up. (margin-left) 10px + (border-left) 5px + (padding-left) 10px + (content) 100px + (padding-right) 10px + (border-right) 5px + (margin-right) 10px = 150 px.
6
Use the same process to determine an element's height.
Tips & Warnings
Internet Explorer for Windows before Version 6 did not correctly implement the box model. Version 6 will implement the box model correctly if the page has the proper DOCTYPE to be in standards mode.
Hacks and/or conditional comments pointing to special style sheets must be used to solve the IE5 and box model bug.