CSS box-sizing property with the border-box value
By default, the width
and height
properties only define the size of a box's content, and padding and border are both added on top of whatever explicit dimensions you set. Let's say you want to create a content box with the width of 300px, and add some padding, borders and margin:
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
The total width of the element will be: 300px + (15px x2) + (50px x2) + (20px x 2) = 470px.
This happens because, by default, the box-sizing
property is set to content-box
. Wouldn't it be cool if we could set the total width of the element with one setting? That's what most developers think. These days, the best practice is to use box-sizing: border-box;
— it includes the padding and border in an element's total width and height.