Box Model: content-box vs border-box. Which one to use?

Sanjit Chakrabarti
2 min readSep 27, 2019

--

Well, let take a look at the picture below:-

normal box
No box. (source:-https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#HTML)

Here, the child is perfectly inside the parent container. By default, box-sizing is set to content-box.

content-box
content-box. (source:-https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#HTML)

Here, after adding padding+border, the child container goes outside of parent container.

border-box
border-box. (source:-https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#HTML)

Here, after adding border-box, the child container perfectly fit inside the parent container.

So, what happened?

Well, content-box is calculated by adding the actual dimensions of padding + border + content.

Border-box, on the other hand, is calculated by automatically adjusting the dimensions of padding + border + content to fit the given height and width.

Now, there can be a case where parent container is your view-port of the browser. And you may want padding + border + content of the element to fit inside the view-port. In that case, border-box is used so that the element doesn’t go outside the view-port.

Fun-fact: many developers even set border-box for all the elements by:-

*{
box-sizing: border-box;
}

Source:- https://www.w3schools.com/css/css3_box-sizing.asp

Happy coding!

--

--