Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when content + padding + border > width in box-sizing: border-box?

Tags:

css

As I understand it, box-sizing has two values: content-box and border-box.

My question is: when we declare box-sizing: border-box, and the total width of content and padding and border are larger than the width that is declared for the element, how does the browser solve this case?

like image 828
Trần Kim Dự Avatar asked Oct 23 '25 06:10

Trần Kim Dự


1 Answers

The size of the content area will be clamped to zero in order to accommodate as much of the padding and borders as possible, the padding and borders then extend from this zero content area if necessary, and the actual contents, if any, will overflow the padding and/or border area. Note that only the content area is affected; the padding and borders will remain intact. From the spec:

The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified width and height properties. As the content width and height cannot be negative ([CSS21], section 10.2), this computation is floored at 0.

In the following example, the specified width of each .box element is 20px, but the minimum width required by the padding and borders in box-sizing: border-box is 5 + 10 + 10 + 5 = 30px. The content width is clamped to zero and the used width of the element is 30px, not 20px, as shown by the .control element which is explicitly and exactly 30 pixels wide. The image, itself being much wider, overflows the element (but anything with a width greater than zero will overflow the element anyway). And since overflow takes place, the content may or may not be clipped according to the overflow property set for the element.

.control {
  width: 30px;
  height: 1em;
  background-color: #000;
}

.box {
  width: 20px;
  margin: 1em 0;
  border: 5px solid #000;
  padding: 10px;
  box-sizing: border-box;
}

.box + .box {
  overflow: hidden;
}
<div class="control"></div>
<div class="box">
  <img src="http://placehold.it/50x50" alt="Image">
</div>
<div class="box">
  <img src="http://placehold.it/50x50" alt="Image">
</div>
like image 189
BoltClock Avatar answered Oct 25 '25 19:10

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!