Easy Tutorial
❮ Css3 2Dtransforms Css Grouping Nesting ❯

CSS Box Model


CSS Box Model

All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design and layout.

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

The box model allows us to place a border around elements and space elements in relation to other elements.

The following image illustrates the box model:

Explanation of the different parts:

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


Width and Height of an Element

Important: When you specify the width and height properties of an element with CSS, you just set the width and height of the content area. To know the full size of an element, you must also add padding, borders, and margins.

In the following example, the total width of the element is 450px:

Example

div {
    width: 300px;
    border: 25px solid green;
    padding: 25px;
    margin: 25px;
}

Let's calculate it:

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

Example

div {
    width: 220px;
    padding: 10px;
    border: 5px solid gray;
    margin: 0; 
}

The final width of an element is calculated like this:

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

The final height of an element is calculated like this:

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 as per the diagram above. However, IE5 and 6 render incorrectly. According to the W3C specification, the space taken by an element's content is set by the width property, and padding and border values are calculated separately. Unfortunately, IE5.X and 6 use their non-standard box model in quirks mode. In these browsers, the width property is not just the content's width but the sum of content, padding, and border widths.

Although there are ways to fix this issue, the best current solution is to avoid it. That is, do not add padding with a specified width to elements; instead, try adding padding or margins to the parent or child elements.

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

To resolve compatibility issues with IE8 and earlier, you can declare in your HTML page.

❮ Css3 2Dtransforms Css Grouping Nesting ❯