DEV Community

Davisson
Davisson

Posted on

Box-sizing model

Measuring by the visible pink border, how wide is the .box element in the following scenario, assuming no other CSS has been applied?

<style>
  .parent {
    width: 200px;
  }
  .box {
    width: 100%;
    border: 2px solid hotpink;
    padding: 20px;
  }
</style>
<div class="parent">
  <div class="box"></div>
</div>
Enter fullscreen mode Exit fullscreen mode

Our .box element has width: 100%. Because its parent is 200px wide, that 100% will resolve to 200px.

But where does it apply that 200px width? By default, it will apply that size to the content box.

If you're not familiar, the “content box” is the rectangle in the box model that actually holds the content, inside the border and the padding:

Image description

The width: 100% declaration will set the .box's content-box to 200px. The padding will add an extra 40px (20px on each side). The border adds a final 4px (2px on each side). When we do the math, the visible pink rectangle will be 244px wide.

When we try and cram a 244px box into a 200px-wide parent, it overflows:

This behavior is weird, right? Fortunately, we can change it, by setting the following rule:

*, *::before, *::after {
  box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

With this rule applied, percentages will resolve based on the border-box. In the example above, our pink box would be 200px, and the inner content-box would shrink down to 156px (200px - 40px - 4px).

This is a must-have rule, in my opinion. It makes CSS significantly nicer to work with.

We apply it to all elements and pseudo-elements using the wildcard selector (*).

Top comments (2)

Collapse
 
alohci profile image
Nicholas Stimpson

It all depends on whether what you're interested in is the screen space, or the natural dimensions of the content. For example, if you've got a 200px x 300px image, you might want to display that unscaled. In that case, you want content-box. Similarly, if you want a box to show the first 10 characters of a monospaced text string, then again you size for the characters, and you don't want the padding and border to take away from that. This works well with flexbox, where another element can use up the remainder of the space, whatever that resolves to be.

Collapse
 
ekqt profile image
Hector Sosa

Nice blog post! Framing your screenshots would've been chef's kiss! We've built an OSS tool to help with this. Give it a shot and let us know what you think: github.com/ekqt/screenshot We'd appreciate giving it a star on GitHub if you find it helpful! Cheers!