What is the CSS box model and how do margin, border, padding, and content interact?

· Category: HTML & CSS

Short answer

The CSS box model describes how every HTML element is a rectangular box made up of content, padding, border, and margin. The box-sizing property controls whether padding and border are included in an element's total width and height.

How it works

  • Content box: The area where text and images appear.
  • Padding: Clears space around the content inside the border.
  • Border: Surrounds the padding and content.
  • Margin: Clears space outside the border, separating the element from others.

With box-sizing: content-box (the default), width and height apply only to the content area. With box-sizing: border-box, width and height include padding and border, which makes layouts more predictable.

Example

* {
  box-sizing: border-box;
}

.card {
  width: 300px;
  padding: 20px;
  border: 5px solid #333;
  margin: 10px;
}

Why it matters

Using border-box globally is a widely accepted best practice because it simplifies mental math when building grid systems and responsive layouts. Without it, adding padding or borders to an element often breaks the intended width.