box-sizing Reset
Overview
By default, CSS calculates an element's total width by adding the Padding and Border ON TOP OF the declared width. This is called content-box and it is a historical nightmare. If you declare a container to be width: 100% and add padding: 20px, it becomes 100% + 40px wide, violently exploding out of its parent and causing a horizontal scrollbar. The box-sizing: border-box property fixes this by forcing the browser to absorb the padding and border into the declared width, rather than adding to it.
Syntax
/* The Universal Box Sizing Reset (Used in EVERY modern project) */
*,
*::before,
*::after {
/* Forces Padding and Border to shrink the content area inward,
rather than expanding the total width outward. */
box-sizing: border-box;
}
.box {
/* With border-box, this element will be EXACTLY 300px wide on screen,
regardless of how much padding we add. */
width: 300px;
padding: 50px;
border: 10px solid black;
}Common Pitfalls
- Forgetting to include
*::beforeand*::afterin the universal reset. Pseudo-elements generate their own boxes, and if they don't inherit theborder-boxfix, they will break your layouts just like normal elements. - Trying to build a complex CSS Grid or Flexbox layout without applying this reset first. Without it, flex children with padding will overflow their tracks uncontrollably.
Interview Questions
content-box and border-box?content-box (default) adds padding and borders on top of the declared width/height, increasing the element's footprint. border-box forces the element to strictly respect the declared width/height, shrinking the internal content area to make room for the padding and borders.
Real-World Example
Why Tailwind CSS injects the border-box reset immediately before doing anything else.
/* Inside Tailwind's preflight.css */
*, ::before, ::after {
box-sizing: border-box;
border-width: 0;
border-style: solid;
border-color: #e5e7eb;
}Check Your Knowledge
Test your understanding of box-sizing Reset with these quick questions.