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.
The
box-sizingCSS 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:
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:
Leave a Reply