1️⃣ The Four Layers

The CSS Box Model is the core concept that defines how elements are sized and spaced in a web page. Every element is treated as a rectangular box with four layers: content, padding, border, and margin.

  • Content: Text or images inside the element.
  • Padding: Space between content and border.
  • Border: Surrounds the padding and content.
  • Margin: Space between the element and neighbors.

2️⃣ Visual Example

CSS Box Model illustration showing layers: content, padding, border, margin.

3️⃣ Practical Code

div.box {
  width: 200px;
  padding: 20px;
  border: 5px solid #3498db;
  margin: 15px;
  background: #ecf0f1;
}

The total element width = content + padding + border + margin.
Here, total width = 200 + (20×2) + (5×2) + (15×2) = 280px.


4️⃣ Border-Box Sizing

Use box-sizing: border-box; to include padding and border inside the declared width and height:

* {
  box-sizing: border-box;
}

Conclusion

Mastering the CSS Box Model ensures precise, responsive layouts and avoids unexpected overflow or spacing issues. Combine box-sizing and modern CSS units to create flexible, accessible designs.