What does * { box-sizing: border-box; } do? What are its advantages?

Technology CommunityCategory: CSSWhat does * { box-sizing: border-box; } do? What are its advantages?
VietMX Staff asked 3 years ago
  • By default, elements have box-sizing: content-box applied, and only the content size is being accounted for.
  • box-sizing: border-box changes how the width and height of elements are being calculated, border and padding are also being included in the calculation.
  • The height of an element is now calculated by the content’s height + vertical padding + vertical border width.
  • The width of an element is now calculated by the content’s width + horizontal padding + horizontal border width.

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>