the 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 essentially wraps the HTML element, and it consists of: margins, borders, padding, and the actual content.
The box model allows us to add a border around elements, and to define space between elements.
The following diagram illustrates the box model:
Explanation of different parts:
- Margin: Clears an area outside the border. The margin is transparent.
- Border: A border that goes around the padding and content.
- Padding: Clears an area around the content. The padding is transparent.
- Content: The content of the box, where text and images appear.
To correctly set the width and height of an element in all browsers, you need to understand how the box model works.
Element Width and Height
Important: When you set the width and height properties of an element with CSS, you are setting the width and height of the content area. To calculate the full size of the element, you must also add padding, borders, and margins.
The total width of the element in the following example is 450px:
div {
width: 300px;
border: 25px solid green;
padding: 25px;
margin: 25px;
}
Let's calculate:
- 300px (width)
- + 50px (left + right padding)
- + 50px (left + right border)
- + 50px (left + right margin)
- = 450px
Imagine you have only 250 pixels of space. Let's set the total width of the element to 250 pixels:
div {
width: 220px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
The formula to calculate the total width of an element is:
Total Element Width = width + left padding + right padding + left border + right border + left margin + right margin
The formula to calculate the total height of an element is:
Total Element Height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
Browser Compatibility Issues
Once the appropriate DTD is set for the page, most browsers will render the content as shown in the diagram above. However, IE5 and IE6 render the box model incorrectly. According to the W3C specification, the space occupied by the element's content is set by the width property, and the padding and border values are added outside of that space. Unfortunately, IE5.x and IE6 in quirks mode use their own non-standard model. In these browsers, the width property includes the content, padding, and border widths.
There are ways to solve this issue. The best solution is to avoid the problem by not setting padding on elements with specified widths. Instead, try to apply padding or margins to the parent and child elements.
IE8 and earlier versions do not support setting the width and border-width properties for padding.
The solution for IE8 and earlier versions compatibility issues is to declare <!DOCTYPE html>
in the HTML page.