Beginner20 min read

The Box Model

Understand the CSS box model — content, padding, border, and margin — and learn how box-sizing controls how element dimensions are calculated.

Every Element is a Box

In CSS, every HTML element is treated as a rectangular box. The box model describes the space an element occupies and consists of four layers, from inside to outside:

  1. Content — The actual content of the element (text, images, etc.). Controlled by width and height.
  2. Padding — Space between the content and the border. Padding is transparent and pushes the border outward from the content.
  3. Border — A visible (or invisible) edge around the padding. You can control its width, style, and color.
  4. Margin — Space outside the border that separates the element from neighboring elements. Margins are always transparent.

Understanding the box model is essential because it directly affects layout. The total space an element takes up is the sum of its content, padding, border, and margin.

Box Model Properties

html
<style>
  .box {
    width: 200px;
    height: 100px;
    padding: 20px;
    border: 3px solid darkblue;
    margin: 16px;
    background-color: lightyellow;
  }
</style>

<div class="box">This box has padding, border, and margin.</div>

<!--
  Total width = 200 + 20*2 + 3*2 + 16*2 = 278px
  (content + padding + border + margin)
-->

box-sizing: border-box

By default, width and height only apply to the content area. Padding and border are added on top, making the element larger than the specified width. This is called content-box sizing and it often leads to unexpected layout issues.

The border-box model changes this behavior so that width and height include padding and border. The content area shrinks to accommodate them:

css
.box {
  box-sizing: border-box;
  width: 200px;
  padding: 20px;
  border: 3px solid black;
}
/* Total width is exactly 200px */
/* Content area = 200 - 40 - 6 = 154px */

Most modern CSS resets apply border-box to all elements:

css
*, *::before, *::after {
  box-sizing: border-box;
}

This makes sizing much more predictable and is considered a best practice.

An element has width: 200px, padding: 10px on all sides, and border: 5px solid. With the default box-sizing (content-box), what is the total rendered width?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.