Sobes.tech
Junior

What is the box-sizing: border-box property and what role does it play in CSS?

sobes.tech AI

Answer from AI

The box-sizing property determines how the total width and height of an element are calculated.

box-sizing: content-box (default value) — width and height only refer to the content. Padding and border are added to the specified width/height values.

box-sizing: border-box — width and height include padding and border. The content shrinks to fit within the specified width/height.

The role of box-sizing: border-box in CSS:

  • Simplifies calculations: Makes it easier to calculate element sizes, especially when using padding and border.
  • Predictable layout: Allows precise setting of block sizes, regardless of padding and border, making layout more predictable.
  • Convenience in block model: Aligns with the intuitive understanding of a block's size — its borders. Simplifies creating grids and fixed-size components.

Example:

.element-content-box {
  width: 100px;
  height: 100px;
  padding: 10px;
  border: 1px solid black;
  box-sizing: content-box; /* Total width = 100 + 10*2 + 1*2 = 122px */
  /* Total height = 100 + 10*2 + 1*2 = 122px */
}

.element-border-box {
  width: 100px;
  height: 100px;
  padding: 10px;
  border: 1px solid black;
  box-sizing: border-box; /* Total width = 100px */
  /* Total height = 100px */
  /* Content will occupy 100 - 10*2 - 1*2 = 78px in width/height */
}