benjaminolsen.dev

Make space with the box model

What you will learn

Every rendered element has a box. Content occupies the inside. Padding separates the content from its border. Margin creates space outside the border. When a box looks too wide, inspect these parts separately instead of reducing the text until it appears to fit.

With the default box-sizing: content-box, width describes the content width. A 280px content box with 20px padding on each side and a 2px border on each side occupies 324px before any margin. The calculation is 280 + 40 + 4. A parent that is only 300px wide cannot contain that outer box.

box-sizing: border-box includes padding and border in the stated width. Margin is still outside. Apply it consistently with *, *::before, *::after { box-sizing: border-box; }. The asterisk selects all elements; the additional selectors cover generated before and after boxes.

A border-box can still overflow if its stated width is greater than the parent. Use width: 100% with an appropriate max-width for a box that should fit small spaces but stop growing on wide screens. Give paragraphs normal line wrapping and avoid fixed heights for text containers.

The example uses normal block layout. margin-inline: auto centres a constrained block horizontally, while padding keeps text away from its edge. Change one property at a time and inspect the result. Some adjacent vertical margins can collapse in normal flow; padding is inside the element and does not behave that way.

Working example

The HTML shown here is the body fragment. The download includes the complete document.

<main class="card"><h1>Room to read</h1><p>A box should leave space for its content and fit the available width.</p></main>

styles.css

*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; padding: 1rem; font-family: Arial, sans-serif; }
.card { width: 100%; max-width: 40rem; margin-inline: auto; padding: 1.5rem; border: 2px solid #35685a; }

Open in browser editor

Download working example

Try a change

Open the page in a narrow browser window. Temporarily change .card to width: 600px. Observe the overflow, then restore width: 100%. Increase padding from 1.5rem to 2rem.

What you should observe

The fixed 600px width can exceed a narrow window. Restoring 100% lets the border-box fit; larger padding reduces the room for content inside that box.

Check your understanding

Does border-box include margin in width?

Read the explanation

No. It includes content, padding and border. Margin remains outside and can still contribute to overflow.