CSS Box-Sizing: A Web Developers’ Exploration

It’s supposed to fit in the right spot!

Alright so we’ve all been there, while we are trying to create the layout of our website we want to give it a border and then BLAM-MO! All of the sudden all of the CSS you’ve been working on goes on the fritz and your whole layout looks like some weird mismatch of parent elements being smaller than your child elements.

Why did that happen?!
Why did that happen?!

You think to yourself “I could have sworn I used 100%” and you double back and see that you have. So now you’re left wonder what happened, well it might be because you don’t know about the Box-Sizing attribute.

Box-Sizing has 3 possible behaviors it can use; content-box, border-box, and padding-box. For the purposes of this article we’ll focus on the first 2 since padding-box doesn’t really translate outside of Firefox.

Content-box

Content-box gives a lot of CSS beginners headaches as you don’t really know that it’s the default value for all of your CSS elements. Its hard to find out how the Content-box style derived from, but it seems that users were working were forced to use the Flexible Box Model which when used would allow box dimensions to be manipulated. Content Box determines that when an element is created it’s content determining factor in the box’s over all real estate.

Content Box
Content Box

Let’s say you have a <div id="parent"> inside of another <div id="child">. We’ll have the parent div occupy 50% of the page. Which means that without border, margin, or padding, our content will occupy 50% of the page. If we determine that the child will be 100% of the width of the parent, well the content will fit 100%, but once we try to add more to it the content will still be at 100% and the rest will go around it.

Box-Model

In comes Box-Model, this behavior says that once the box has a determined width and height, that’s it. The Padding, Border and Margins all have to fit within those specific dimensions. This is a relief because you know how big your box will actually be.

Look at that sweet exact sizing

Keep in mind that there are probably tons of layouts and legacy sites that use the default content-box and so it’s import to know what you’re dealing with once you get into an older developed site.

Box Model for us can definitely help create sites that are more responsive and fit better as more and more screen sizes exists. So if you haven’t changed your default box-sizing try it out and find out what you’ve been missing out on.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store