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,widthsets only the content. Padding and border are added on top, sowidth: 200px; padding: 20px; border: 1pxrenders 242px wide. - With
box-sizing: border-box,widthincludes 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?