DEV Community

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

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

3 1

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

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post