CSS Box Model

The CSS Box Model describes how the size of an element is calculated and how its content, padding, border, and margin interact. Understanding the box model is essential for controlling layout and spacing in web design.

Box Model Components

Every element in CSS is a rectangular box made up of four main components:

Box-Sizing Property

The box-sizing property allows you to control whether padding and border are included in the element's total width and height.

/* Default: width + padding + border not included */
div {
  box-sizing: content-box;
}

/* Include padding and border in element's total width and height */
div {
  box-sizing: border-box;
}

Example Box Model

Consider an element with width: 200px, padding: 10px, border: 5px, and margin: 20px.

.element {
  width: 200px;
  padding: 10px;
  border: 5px solid #333;
  margin: 20px;
  box-sizing: content-box; /* default */
}

The total space occupied by the element horizontally will be: width + padding-left + padding-right + border-left + border-right + margin-left + margin-right

Best Practices for Box Model

Common Mistakes with Box Model

Tip: Setting *, *::before, *::after { box-sizing: border-box; } globally helps maintain consistent layouts across your website.