Header

~Articles This Week~

~Box Sizing~

By StarsInDust



Table of Contents

 

What is Box Sizing?

Test this out for yourself

How can we fix this Box Sizing Madness?

What happens when we add text?

What is Box Sizing?

~back to top~

Well, box sizing is when you tell an element, like a div or an image to be a certain size; you expect it to be that size; and then it confuses the mess out of you when it comes in at some other size.

This is because (by default), a web element will not just be the width and the height alone. Oh, it would be so simple if it would. It wants to include both what you state as the padding, and even the border. Thank goodness that the margin is the space around and out side of an element, or the darn thing would be throwing that in too.

Test this out for yourself

~back to top~

You can test this madness out for yourself if you make 4 different divs. Give each div the same width and height and then give one a border and one some padding. Leave the first div with just the width and the height

HTML

 

CSS

How can we fix this Box Sizing Madness?

~back to top~

Yes, this can be absolutely enough to drive a young web site developer to lose their ever-loving mind. Especially when you have no idea where this extra sizing is coming from and you go and add even more padding and borders, and the darn thing just gets more and more unruly.

Why these people who write these initial codes did not think about this is beyond me, but alas, we do have a fix for this. Even if we have to write our own rules to fix it.

Ok, now this is what I used to fix this problem. Add this to your CSS

What happens when we add text?

~back to top~

Well, since we gave our boxes a specific height and width here, if we were to add text, it would over flow the boxes.

The last box here had the height in the CSS changed to auto, so that it would not overflow.

Additionally, you could just leave the height off, in your CSS code, and the box would accommodate the overflow of the text automatically.

In the red box, we just left the height blank, and it worked fine.

So, where the box-sizing fix can be great for making sure that the width of your boxes are the same width, without the hassle of always having to figure in the border size and padding, it could break things in other places, especially if we do not understand what is going on.

However, fixing this common problem really was not all that hard, and let us discover some of the other inner workings of our CSS.