TechnicalEasy HTML & CSS

Explain the CSS box model and what box-sizing: border-box does.

Asked for Frontend Developer, Full-Stack Developer

Why they ask this: Layout bugs often come from misunderstanding widths, padding and borders.

Answer

Every element is a box made of four layers, from inside out: content → padding → border → margin.

  • With the default box-sizing: content-box, width sets only the content. Padding and border are added on top, so width: 200px; padding: 20px; border: 1px renders 242px wide.
  • With box-sizing: border-box, width includes padding and border, so the element stays 200px wide. This is far easier to reason about.
css
*, *::before, *::after {
  box-sizing: border-box;
}

Margins are outside the box and can collapse: vertical margins of adjacent block elements combine into the larger of the two instead of adding up.

Can you explain this in your own words?

Back to question bank