CSS: Box Sizing and Border Box
The CSS property of box-sizing
lets the developer control the dimensions, both
width and height, of an HTML element.
📑 box-sizing - MDN
Using the border-box
value for box-sizing
makes the browser include
the element's border
AND padding
values in the width and height
allocations. The content area will automatically shrink to account for this additions versus
rendering using the default content-box
, where the content equals the width or
height set for the element.
Example
Here is an example of a div
element with a border
and
padding
set. The box-sizing
property is set to
border-box
so the width and height of the element will include the border and
padding.
Here is a CSS rule for div elements that defines the width and box model. The content is 400 pixels wide and the height is driven by the actual (but not shown) content, whatever it happens to be.
div {
width: 400px;
margin: 10px;
border: 1px solid #000000;
padding: 15px;
background-color: #247247;
color: #ffffff;
}
Now apply the box-sizing property of border-box to this same example.
Note the difference
in the content dimensions (blue shaded area):
div {
box-sizing: border-box;
width: 400px;
margin: 10px;
border: 1px solid #000000;
padding: 15px;
background-color: #247247;
color: #ffffff;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}