Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

CSS Box Model

CSS Box Model


CSS Box Model

All HTML elements can be viewed as boxes. In CSS, the term "box model" is used when designing and laying out pages.

The CSS box model is essentially a box that wraps around HTML elements. It consists of: margins, borders, padding, and the actual content.

The box model allows us to place elements in the space between other elements and the borders of surrounding elements.

The following image illustrates the box model:

Explanation of the different parts:

To correctly set the width and height of elements in all browsers, you need to understand how the box model works.


Element Width and Height

RemarkImportant: When you specify the width and height properties of a CSS element, you are only setting the width and height of the content area. To know the full size of an element, you must also add padding, borders, and margins.

The total width of the element in the following example is 450px:

Example

div

{

width:

300

px

;

border:

25

px

solid

green

;

padding:

25

px

;

margin:

25

px

;

}

Try it »

Let's calculate it ourselves:
300px (width)

Imagine you only have 250 pixels of space. Let's set the total width of the element to 250 pixels:

Example

div

{

width:

220

px

;

padding:

10

px

;

border:

5

px

solid

gray

;

margin:

0

;

}

Try it »

The formula for calculating the total width of the final element is as follows:

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The formula for calculating the total height of the final element is as follows:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin


Browser Compatibility Issues

Once a proper DTD is set for the page, most browsers will render content according to the diagram above. However, IE 5 and 6 render it incorrectly. According to the W3C specification, the space occupied by element content is set by the width property, while the padding and border values around the content are calculated separately. Unfortunately, IE5.X and 6 use their own non-standard model in quirks mode. In these browsers, the width property is not the width of the content, but the sum of the widths of the content, padding, and border.

Although there are ways to solve this problem, the best solution at present is to avoid it. That is, do not add padding with a specified width to an element; instead, try adding padding or margins to the element's parent and child elements.

IE8 and earlier versions do not support setting the width of the padding and border properties.

To solve the incompatibility issue with IE8 and earlier versions, you can simply add a declaration in the HTML page.