Note to Self — Guide on CSS Box-Sizing

Tek Loon
2 min readDec 21, 2019

--

Photo by Sai Kiran Anagani on Unsplash

This is my own summarized understanding of CSS box-sizing property. After going through several courses and articles about web development. You will realize the most of the courses recommend the following simplest best practice for box-sizing:

* {
box-sizing: border-box;
}

For quite a while, I am just reusing this boilerplate code and forget the reason and what’s the purpose of having this code. So I wrote this article to enhance my understanding and hardwired this into my brain and serves as a place where I could redirect if my fellow teammates asked me why you choose to use border-box.

Why border-box?

The first question you always have is whyborder-box is the most popular and recommended the box-sizing method. The reason is fairly simple. It’s because straightforward and intuitive.

Straightforward

It is straightforward in terms of specifying the width of the element. When you’re trying to specifying the width of the element with the following code.

{
width: 300px;
padding: 20px;
border: 5px solid black;
}

As human beings, we tend to interpret this element to have a total width of 300px, which is wrong in this scenario. Instead, the total width of the element is: 350px.

box-sizing: content-box

However, if we declare box-sizing: border-box. The width of the container will factor in the padding and border width as well which equivalent to: 300px.

box-sizing: border-box

This means no matter how much border and padding you have set, the width of the element is still similar to what you specify in the width property, which 300px in this example.

Codepen Example:

Simple Example with Box-Sizing

Conclusion

Due to this situation, it’s counterintuitive and counterproductive if we every time we have to calculate the element width by ourselves. It’s even more impossible to calculate the width via

Using border-box approach, it makes the development experience much better.

However, there is a slightly better practice for box-sizing which I will explore and write about later. It’s about inheriting the box-sizing.

References

--

--

Tek Loon
Tek Loon

Written by Tek Loon

Coder and Writer. If you enjoy my stories— support me by https://www.buymeacoffee.com/tekloon so I can keep writing articles for the community.

No responses yet