Decide what width includes
box-sizing changes how an explicit width or height relates to padding and border. Under content-box, width describes only the content box. Under border-box, width includes content, padding and border, making many component layouts easier to size.
.content {
box-sizing: content-box;
width: 240px;
padding: 20px;
border: 2px solid;
}
.border {
box-sizing: border-box;
width: 240px;
padding: 20px;
border: 2px solid;
}The first box has a 284px border-box width. The second has a 240px border-box width and a 196px content width. Margins are excluded in both cases.
A useful baseline
*, *::before, *::after {
box-sizing: border-box;
}
.form-control {
width: 100%;
padding: 0.75rem;
border: 1px solid #64748b;
}A full-width form control can now include its padding and border within the intended available width. Without border-box, adding padding to width:100% can make the border box wider than its containing block.
What border-box does not solve
It does not include margins in width. It does not prevent a long unbroken word, intrinsic image size or a flex item's minimum size from causing overflow. It also does not give an element a useful responsive maximum width automatically. Diagnose each constraint rather than assuming one reset fixes every layout.
Inheritance option
box-sizing is not inherited by default. Another baseline sets it on html and uses inherit on all elements and pseudo-elements. That makes it possible for a component subtree to choose another box model deliberately. Use one understandable convention consistently within a project.
Practice and answer
- Create two equal-width cards with the examples above and compare their measured border boxes.
- For border-box width 300px, 24px padding on each side and 1px borders, calculate the content width. Answer: 250px.
- Add 10px horizontal margins and explain why the outer width still increases.
- Test a width:100% input inside a narrow form and inspect for horizontal scrolling.