Utilizor
Contact Us

CSS Box Model

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

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 image below illustrates the box model:

Margin
Border
Padding
Content

Example 1: Demonstrating the Box Model

This example demonstrates the box model by setting values for margin, border, padding, and content width.

This text is the content of the box. We have added a 50px padding, 20px margin and a 15px green border.

Example 2: Calculating Total Width

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

Total width = 320px (width) + 20px (left + right padding) + 10px (left + right border) + 0px (left + right margin) = 350px

Example 3: Box Sizing Border Box

The box-sizing: border-box; property allows us to include the padding and border in an element's total width and height.

With box-sizing: border-box, the total width remains 300px.

Example 4: Comparison

Compare two divs, one with default box-sizing and one with border-box.

Default (Content Box)
Border Box

Example

div {
  width: 300px;
  border: 15px solid green;
  padding: 50px;
  margin: 20px;
}