CSS - box-sizing

The standard calculation of width and height in CSS looks like this:

Width + Padding + Border = Actual Width Height + Padding + Border = Actual Height

This means that the elements are always larger than we specify. There are several ways to prevent this. In this article I will show you two and only one is the right one that causes at least headache.

For both examples we use the following example code:

.div1 {
  width: 200px;
  height: 100px;
  border: 1px solid red;
}
.div2 {
  width: 200px;
  height: 100px;
  padding: 50px;
  border: 1px solid blue;
}

CodeSandbox

Even if the two divs are defined with the same sizes, they are still different in size. As described above, this is due to the calculation of the divs. Now you could simply say we subtract the padding from the height and the width. Then it could look like this:

.div1 {
  width: 200px;
  height: 100px;
  border: 1px solid red;
}
.div2 {
  width: calc(200px - 50px * 2);
  height: calc(100px - 50px * 2);
  padding: 50px;
  border: 1px solid blue;
}

CodeSandbox

or

.div1 {
  width: 200px;
  height: 100px;
  border: 1px solid red;
}
.div2 {
  width: 100px;
  height: 0px;
  padding: 50px;
  border: 1px solid blue;
}

CodeSandbox

With such a simple example this might be understandable but there are much more complicated cases where this is not so easy. At the latest when you want to make adjustments, this can cause big problems very quickly. So that we do not have to worry about these calculations we can use "box-sizing".

With this our code looks like this:

* {
  box-sizing: border-box;
}
.div1 {
  width: 200px;
  height: 100px;
  border: 1px solid red;
}
.div2 {
  width: 200px;
  height: 100px;
  padding: 50px;
  border: 1px solid blue;
}

The "box-sizing: border-box" prevents that our elements can grow beyond their actual size. Therefore our elements always remain in exactly the specified size.

In this case we have given all available HTML elements this property with the Wildcard Operator. Of course you can also apply this to single elements.