Quiz

Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.

Topics
CSS

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:

  1. Content: Text, images, or child elements.
  2. Padding: Space between the content and border; the element's background extends through it.
  3. Border: The line surrounding the padding and content.
  4. 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 sizingContent widthBorder-box width
content-box100px100px + 20px + 10px = 130px
border-box100px - 20px - 10px = 70px100px

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.

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

An element has width: 200px, padding: 20px on each side, and a 5px border on each side. What is its border-box width with box-sizing: content-box?