Understand the idea
An element can generate one or more layout boxes, each with content, padding, a border and a margin. Some elements, such as those with display: none, generate no box. When a card unexpectedly overflows its container, these layers are a good place to look.
With content-box, width sets the content width; padding and borders add to it. With border-box, the declared width includes the content, padding and border. Margins remain outside either calculation. Outline does not take up layout space.
Read the example
This is a CSS fragment. Put it in a stylesheet and supply the matching HTML described in the exercise.
*, *::before, *::after {
box-sizing: border-box;
}
.card {
width: 100%;
padding: 24px;
border: 1px solid #777;
}Change it. See why.
Adjust the controls and compare the result with the CSS. Changes stay only in this page’s memory.
A small mistake, explained
What goes wrong
A content-box element at width: 100% with padding can be wider than its parent.
How to fix it. Inspect the box model diagram. Switch to border-box and check whether margins or a minimum width still cause overflow.
Try it yourself
Put a padded card inside a 300px container. Toggle box-sizing and compare its measured width.
Further reading
Keep exploring
- CSS · Guide
Find the source of horizontal overflowFix the oversized element instead of hiding the symptom.
- CSS · Guide
Why a huge z-index can still loseUnderstand the group an element belongs to before raising its number.