DevAcademy
LearnCSSThe Box Model
BeginnerCSS

The Box Model

Understand how every element is treated as a box made of content, padding, border, and margin.

Reading Time

16 min

Lesson

Lesson 7 of 30

Every Element is a Box

CSS treats every HTML element as a rectangular box, made up of four layers: the content, padding, border, and margin — from innermost to outermost.

Box Model Layers

LayerDescription
ContentThe actual text, image, or other content
PaddingTransparent space between the content and the border
BorderA line that wraps the padding and content
MarginTransparent space outside the border, separating it from other elements

Visualizing the Box Model

<style>
  .box {
    width: 200px;
    padding: 20px;
    border: 4px solid steelblue;
    margin: 20px;
    background: #eef4fb;
  }
</style>

<div class="box">Content area</div>
Output

Calculating Total Size

By default, an element’s total rendered width is width + padding-left + padding-right + border-left + border-right (margin is separate space outside the box, not part of its size).

Default Size Calculation

.box {
  width: 200px;
  padding: 20px;
  border: 4px solid black;
}
/* Rendered width = 200 + 20 + 20 + 4 + 4 = 248px */

box-sizing: border-box

The box-sizing property changes this calculation. With border-box, the width you set already includes padding and border, making sizing far more predictable.

border-box in Action

<style>
  * {
    box-sizing: border-box;
  }
  .box {
    width: 200px;
    padding: 20px;
    border: 4px solid tomato;
    background: #fdeceb;
  }
</style>

<div class="box">Now width stays exactly 200px total.</div>
Output

Default box-sizing Surprises

The default box-sizing value is content-box, which is why adding padding to a fixed-width element often unexpectedly makes it wider than intended.

Best Practice

Apply box-sizing: border-box to every element with a universal selector at the top of your stylesheet. It’s one of the most common resets in real-world CSS.

Interview Questions

Quick Quiz

1. What are the four layers of the box model, from inside out?

2. With the default box-sizing, does padding increase an element’s total rendered width?

3. What does box-sizing: border-box do?