Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

What is box-sizing in CSS

The default way for CSS to calculate the total needed space for an element is to sum up the follwing:
totalwidth = 2*margin + 2*border-width + 2*padding + width.

The above example assumes that all of the left - right margins, paddings, and border-width are equal.

If you have a .container with the width: 100px you will not be able to put 2 .column next to each other if you have a width: 50px and a border: 1px solid red. That is because one column will have 50px + 2*1px = 52px and your container only has 100px. While I was learning CSS this was quite an "Aha!" moment for me.

.column {
    border: 1px solid red; 
    width: 50px; // will actually take 52px 

.container {
    width: 100px; // will not fit 2 columns

But you can change this behavior by setting the box-sizing property.

You can set 2 values for box-sizing:

  • content-box ; the default option
  • border-box

If we set box-sizing: border-box this means that the padding and border-width are included in the width. This can provide provides us with better control for how much space one element will take up.

So, for border-box we will have:
totalwidth = 2*margin + (width - 2*border - 2*padding).

Please note that only the border and padding are included. The margin will still add extra space.

If you want to apply it to every element on the page, out of the box, you can just set:

*, *:before, *:after {
  box-sizing: border-box;
Home Screencasts Best of Newsletter Search X