Box Sizing Property

Box Sizing Property

What's deal with this box-sizing property you see pretty much used in everywhere. That's what we gonna see in this blog.

The box-sizing property can make building CSS layouts a lot easier and more predictable.

Without the CSS box-sizing Property

By default , box sizing is to content box, i.e box-sizing: content-box

This means

the width and height of an element is calculated like this:

width + padding + border = actual width of an element

height + padding + border = actual height of an element

Setting a padding and borders to element expand the width/height of the element than the specified width and height.

Let's understand this with an example

you can see that the specified width and height of .div-1 is 300px and 100px respectively. Let's set the same width/height for .div-2 along with that set padding to 10px border to 5px.

no box-sizing.png

Adding padding to 10px and border 5px increase the actual width of element.

Having the actual visible width of a box turn out differently from what you declared in the CSS. This completely disturb the layout of the page.

Don't worry, The box-sizing property solves this problem.

CSS Box-sizing Property

box-sizing property controls how the total width and height of an element are calculated.

This allows us to include the padding and border in an element's total width and height.

Though box-sizing has three possible values (content-box, padding-box, and border-box), the most popular value is border-box.

Here is what we get if we add box-sizing: border-box in .div-2 from above example. box-sizing.png

On the .box-2, padding 10px and border 5px are included in the width 300px and height 100px.

Using box-sizing property can remove the problems like Oversized elements and Horizontal scrolling. Hence the result is much better if we use border box property.

At last, I would recommend you to use a CSS reset file.

html{
    box-sizing: border-box;
}
*,
*::before,
*::after{
    box-sizing: inherit;
}

With that we can sure that the most important CSS property works as expected. Also it's worth to mentioning that making box-sizing to be inherited is better because it will enable all elements to inherit this box-sizing property from html element default.

I'm always love when I get feedback about my blogs, so don't hesitate to play with the comment/discussion area, like and bookmark this blog if you love it or share with others.

You can follow me on Twitter , You can also fork/clone my projects on Codepen .
If you read up to this point, thank you I appreciate your will to learn and am happy to have you reading this.
Keep Coding, Keep Learning : )