Cyrus Yip's blog

box-sizing in CSS: How Width and Height Are Calculated

Cyrus Yip

In CSS, a block element is a box (rectangle) made up of four parts: content, padding, border, and margin. box-sizing determines how total width and height of an element is calculated.

Box model

By default (box-sizing: content-box;), the width property only sets the width of content, which is very unintuitive. When you set width: 100% and border to a element, it becomes wider than the parent element and its border extends beyond the parent element.

1
2
3
<div class="container">Parent
  <div class="child">Child</div>
</div>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
.container {
  width: 100px;
  height: 100px;
  outline: 1px solid green;
}
.child {
  width: 100%;
  border: 10px solid blue;
  box-sizing: content-box;
}

When we use box-sizing: border-box on the child element, the width property sets the width of content, padding and margin, so the child element won’t be wider than the parent element.

It’s recommended to set border-box to all elements to avoid pitfalls about width and height.

1
2
3
*, *::before, *::after {
  box-sizing: border-box;
}

Further reading:


Image source: the image used in this post is from The box model - Learn web development | MDN#what_is_the_css_box_model.

Tags: