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.

The different parts of the CSS box model are:

Example Box Model

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

Example
<!DOCTYPE html>
<html>
<head>
<style>
.element {
  width: 200px;
  padding: 10px;
  border: 5px solid #333;
  margin: 20px;
  box-sizing: content-box; /* default */
}
</style>
</head>
<body>

<p class="element">Introduction CSS</p>

</body>
</html>
Try this code

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

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;
}

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.