box-sizingThe box-sizing property in CSS controls how the total width and height of an element are calculated. It decides whether the specified width and height apply only to the content, or also include padding and borders.
content-box (default) → width/height apply only to the content.border-box → width/height include content + padding + border.content-box: Padding and border are added on top of the width/height.border-box: Padding and border are included inside the width/height.border-box globally simplifies layout math.| Value | Includes Padding? | Includes Border? | Typical Use Case |
|---|---|---|---|
content-box |
❌ | ❌ | Default box model; precise content sizing. |
border-box |
✅ | ✅ | Modern layouts; predictable element sizes. |
box-sizingControls how the browser calculates an element’s width and height.
/* Syntax for the box-sizing property */
box-sizing: content-box | border-box | inherit;
Commonly used values:
content-box → default behavior in browsers.border-box → recommended for most modern layouts.inherit → inherits the value from the parent element.content-box (Default)Here, the width only applies to the content. Padding and border are added on top of it.
/* Element sized using the default content-box model */
.content-box-example {
width: 200px;
padding: 20px;
border: 5px solid black;
box-sizing: content-box;
}
The final element width is calculated as:
200px20px + 20px = 40px5px + 5px = 10pxTotal width = 200 + 40 + 10 = 250px
border-boxWith border-box, the specified width includes content, padding, and border.
/* Element sized using the border-box model */
.border-box-example {
width: 200px;
padding: 20px;
border: 5px solid black;
box-sizing: border-box;
}
The total width remains exactly 200px:
border-box?Using box-sizing: border-box avoids layout issues when padding and borders increase the element’s size unexpectedly. It is especially useful in responsive designs and is widely recommended for consistent box sizing across your website.
box-sizing: border-box globally for consistent sizing.box-sizing values.Common global pattern:
/* Apply border-box sizing to every element on the page */
* {
box-sizing: border-box;
}
width but different box-sizing values and observe the difference.box-sizing: border-box to build a card layout that fits exactly inside a 300px wide container.30px on a box with content-box and border-box; compare their rendered widths.* { box-sizing: border-box; } and see how it affects an existing layout.box-sizing applied.