gotchacssModeratepending
Gotcha: CSS box-model and width calculation
Viewed 0 times
box-sizingborder-boxcontent-boxwidthpaddingbox model
Error Messages
Problem
Element is wider than expected because padding and border are added to the specified width.
Solution
The default box model adds padding and border OUTSIDE the width:
The
/* DEFAULT (content-box): width = content only */
.box {
width: 200px;
padding: 20px;
border: 1px solid;
/* Actual width: 200 + 20*2 + 1*2 = 242px! */
}
/* FIX: Use border-box */
.box {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 1px solid;
/* Actual width: 200px (content shrinks to 158px) */
}
/* BEST: Apply globally (should be in every project) */
*, *::before, *::after {
box-sizing: border-box;
}
/* Why this breaks layouts: */
.container {
display: flex;
}
.sidebar {
width: 300px;
padding: 20px;
/* content-box: actual width = 340px */
/* border-box: actual width = 300px */
}
.main {
width: calc(100% - 300px);
/* Only correct if sidebar is also 300px actual width! */
}The
box-sizing: border-box reset is so common it's included in every CSS reset/normalize. Without it, responsive layouts become nearly impossible to calculate correctly.Why
The W3C default (content-box) was a design mistake that virtually everyone overrides. border-box makes width mean what you'd expect: the total width of the box.
Context
CSS layouts where elements are wider/taller than expected
Revisions (0)
No revisions yet.