Lets say you wish to create a grid of items having 4 columns, the grid width being 1000px. Now, you can give the boxes a width of 250px (not counting margin for now) and give them a float:left; to make your perfect grid. But what happens when you add borders and padding to the boxes. Well, that actually depends on your browser, most probably the width of the boxes increases leading to the deformation of your setup.
Now, you could say that you will just do some quick calculation and decrease the width of each box to make the grid perfect again. That is true if you are hell bent on using the width of the grid as 1000px. But, we all know that in today’s age of responsiveness, there might be a situation when you need to use percentage values instead of pixels. If that is the case then there is no way that you can achieve your required effect with the current set up.
The Solution?Here comes a CSS property that can help in cases like this:box-sizing. The CSS box-sizing property helps the browser decide that how are the elements going to fit in a certain area.
The three values supported by this property are:
- border-box: My personal favourite. The padding and borders of an element are considered a part of the width/height of the element and any increase in the padding won’t increase the width of the element.
- content-box: In this case the padding and borders are not considered to be a part of the width/height of the element. This is the default case in most browsers since CSS 2.1.
- Inherit: This means that the element will inherit the behaviour from its parent.
background:rgb(179, 179, 255);
<div id="c_box">Shhhh!!!<br>This is supposed to be the content-box.</div>
<div id="b_box">Well, then this probably should border-box.</div>
This is supposed to be the content-box.
More Uses of box-sizingAlthough there might be a debate among many front-end developers about the usefullness of this property but I find it very helpful. Infact I have started using the following in all my CSS Reset code.
I think that that this makes the layout of my websites a bit more logical, which is always a good thing. When I was new to front-end developing (not saying that I am experienced now ) I didn’t use this and had lots of problems in making a website work in different browsers let alone responsiveness.
So, I guess whether you use it or not is up to you but if you have a better method or any comments about this, don’t forget to share!