Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.
TL;DR
Every rendered CSS box has a content area surrounded by padding, a border, and margins. With the default box-sizing: content-box, a declared width applies only to the content. With box-sizing: border-box, it includes the content, padding, and border; margins are excluded in both cases. border-box usually makes component sizing easier to reason about.
Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.
The four areas
From the inside out, the box model consists of:
- Content: Text, images, or child elements.
- Padding: Space between the content and border; the element's background extends through it.
- Border: The line surrounding the padding and content.
- Margin: Transparent space outside the border that separates the element from others.
The width and height properties control different areas depending on box-sizing.
content-box and border-box
Both boxes below declare width: 100px, padding: 10px, and a 5px border:
.content-box {box-sizing: content-box; /* Initial value. */width: 100px;padding: 10px;border: 5px solid;}.border-box {box-sizing: border-box;width: 100px;padding: 10px;border: 5px solid;}
| Box sizing | Content width | Border-box width |
|---|---|---|
content-box | 100px | 100px + 20px + 10px = 130px |
border-box | 100px - 20px - 10px = 70px | 100px |
Neither calculation includes margins. A common project-wide default is:
*,*::before,*::after {box-sizing: border-box;}
This is a sizing convention, not a complete layout system. Intrinsic sizes, min-width, max-width, overflow, and the formatting context can still affect the final used size. For example, width and height normally do not apply to a non-replaced inline element such as a span.
Margins and debugging
Adjacent vertical margins of block boxes in normal flow can collapse into one margin. Margins do not collapse in Flexbox or Grid layout, and box-sizing does not change margin-collapsing behavior.
When a component is unexpectedly too wide, inspect its box-model diagram and computed box-sizing in browser DevTools. This quickly reveals whether padding or borders were added outside a content-box width, or whether a minimum size or overflowing child is the real cause.