CSS Box Model
CSS Box Model
All HTML elements can be viewed as boxes. In CSS, the term "box model" is used for design and layout.
The CSS box model is essentially a box that wraps around HTML elements. It includes: 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:
- Margin- Clears the area outside the border; the margin is transparent.
- Border- A border that goes around the padding and content.
- Padding- Clears the 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 know how the box model works.
Width and height of an element
Important: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 the element, you must also add padding, borders, and margins.
The total width of the element in the example below is 450px:
Example
Try it Yourself »
Let's calculate it ourselves:
300px (width)
+ 50px (left + right padding)
+ 50px (left + right border)
+ 50px (left + right margin)
= 450px
Imagine you only have 250 pixels of space. Let's set an element with a total width of 250 pixels:
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 final formula for calculating the total height of the element is as follows:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
Browser compatibility issues
Once an appropriate DTD is set for the page, most browsers will render content according to the illustration above. However, IE 5 and 6 render it incorrectly. According to the W3C specification, the space occupied by the 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. The width property of these browsers is not the width of the content, but the sum of the widths of content, padding, and borders.
Although there are methods to solve this problem, the best solution currently is to avoid it. That is, do not add padding with a specified width to an element, but instead try adding padding or margin to the element's parent and child elements.
IE8 and earlier versions of IE do not support setting the width properties of padding and border.
To solve the incompatibility issue with IE8 and earlier versions, just declare <!DOCTYPE html> in the HTML page.
other extensions