DEV Community

José Miguel Álvarez Vañó
José Miguel Álvarez Vañó

Posted on • Edited on • Originally published at jmalvarez.dev

box-sizing - How does it work?

Technical explanation

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

box-sizing only accepts two values: content-box and border-box.

box-sizing default value is content-box which means that the width of an element is calculated in the following way:

actual width = width + border-left + border-right + padding-left + padding-right

This way it's sometimes hard to calculate the actual width of an element, specially when using relative values.

Example

In the following example we are using content-box by default. The child element has a width of 100%, a border of 8px and a padding of 4px. The actual width is calculated in the following way (you can inspect the element to check it):

actual width = width 100% + border 8px + padding 4px

content-box example

Instead, if we change box-sizing to border-box the width of the element will take into account the padding and borders. The child component still has a width of 100%, a border of 8px and a padding of 4px, but the actual width is 100%.

border-box example

At the bottom of the article in my website you can play with the following interactive example to see how the width of the child component changes depending on the value of box-sizing.


Resources

Top comments (0)