- By default, elements have
box-sizing: content-boxapplied, and only the content size is being accounted for. box-sizing: border-boxchanges how the width and height of elements are being calculated,borderandpaddingare also being included in the calculation.- The
heightof an element is now calculated by the content’s height + verticalpadding+ verticalborderwidth. - The
widthof an element is now calculated by the content’s width + horizontalpadding+ horizontalborderwidth.
Consider:
div {
width: 160px;
height: 80px;
padding: 20px;
border: 8px solid red;
background: yellow;
}
.content-box {
box-sizing: content-box;
/* Total width: 160px + (2 * 20px) + (2 * 8px) = 216px
Total height: 80px + (2 * 20px) + (2 * 8px) = 136px
Content box width: 160px
Content box height: 80px */
}
.border-box {
box-sizing: border-box;
/* Total width: 160px
Total height: 80px
Content box width: 160px - (2 * 20px) - (2 * 8px) = 104px
Content box height: 80px - (2 * 20px) - (2 * 8px) = 24px */
}
<div class="content-box">Content box</div>
<br>
<div class="border-box">Border box</div>