CPCODELAB
CSS

The Box Model: Content, Padding, Border, Margin

10 min read

Every Element Is a Box

In CSS, every element is rendered as a rectangular box. That box has four layers, from inside to outside: content, padding, border, and margin. Understanding how these interact is fundamental to controlling layout.

css
.box {
  /* Content area */
  width: 300px;
  height: 150px;

  /* Space inside the border */
  padding: 16px;

  /* The border itself */
  border: 2px solid #6366f1;

  /* Space outside the border */
  margin: 24px;
}

box-sizing: border-box

By default, width and height apply only to the content area. Padding and border are added on top, making the actual rendered size larger than you set. Setting box-sizing: border-box changes this so that width and height include padding and border — which is almost always what you want.

css
/* Apply border-box globally — do this in every project */
*, *::before, *::after {
  box-sizing: border-box;
}

/* Now this box is exactly 300px wide, not 300+padding+border */
.box {
  width: 300px;
  padding: 16px;
  border: 2px solid #6366f1;
}

Without box-sizing: border-box, a width: 100% element with padding will overflow its parent. This is one of the most common layout bugs in CSS.

Ready to test yourself?
Practice CSS— quiz & coding exercises