WDD 130: Web Fundamentals

CSS: Box Sizing and Border Box

The CSS property of box-sizing lets the developer control the dimensions, both width and height, of an HTML element.

"By default in the CSS box model, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen. This means that when you set width and height, you have to adjust the value you give to allow for any border or padding that may be added."
📑 box-sizing - MDN

Using the border-box value for box-sizing makes the browser include the element's border AND padding values in the width and height allocations. The content area will automatically shrink to account for this additions versus rendering using the default content-box, where the content equals the width or height set for the element.

Example

Here is an example of a div element with a border and padding set. The box-sizing property is set to border-box so the width and height of the element will include the border and padding.

Here is a CSS rule for div elements that defines the width and box model. The content is 400 pixels wide and the height is driven by the actual (but not shown) content, whatever it happens to be.

div {
  width: 400px;
  margin: 10px;
  border: 1px solid #000000;
  padding: 15px;
  background-color: #247247;
  color: #ffffff;
}
Box Model Labeled Dimensions w/out border-box

Now apply the box-sizing property of border-box to this same example.
Note the difference in the content dimensions (blue shaded area):

div {
  box-sizing: border-box;
  width: 400px;
  margin: 10px;
  border: 1px solid #000000;
  padding: 15px;
  background-color: #247247;
  color: #ffffff;
}
Box Model Labeled Dimensions w/out border-box
Some common 'reset' natured CSS declarations using the universal selector include setting the box-sizing to border-box in order for all elements to follow this method.
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}