How to use the css box-sizing property

Understanding css box-sizing is critical to proper layout at the page and component level.

In this post I’m going to document how box-sizing works and how it can solve alignment and layout issues.

According to MDN docs:

The box-sizing CSS property sets how the total width and height of an element is calculated.

The TL;DR on this is that the default value of content-box excludes the border when calculating width and height, while border-box includes it.

The primary ramifications are that content-box may result in this:

Even with a width that matches the interior of the parent box, adding a border to the child box pushes it’s width past the container.

In the example above, the div for the smaller box is nested inside of the larger box and assigned a width of 100%, which one might expect should effectively give it the same exact width as the larger box. However, using content-box, that width is first set to 100% and then the border is additionally added- making the total rendered box wider that the parent element.

You may notice that the left outside border edge of the gray box site just inside the inside left edge of the parent box- since the box is nested it aligns horizontally on the inside edge of the parent box.

So it’s easy to see how this could be problematic. When one needs to nest a bordered div at full-width inside of another div, the results can be undesireable.

This is where border-box comes in. Apply border-box as the value to box-sizing can give you this:

When set to border-box, the padding is included into the calculated width inclusively. The padding is essentially added to the ‘inside’ of the width.

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *