box-sizing
in Flexbox
You size the flex item content box by default
box-sizing
lets you specify if sizing properties should be sizing the content box or the border box area of a box.
When sizing boxes, we often consider the border and padding to optically belong to the box. When we say that a box is 100 pixels wide, we usually mean that the border and padding are included in that measurement.
Because the initial value of box-sizing
is content-box
, all sizing properties will be sizing the content box, and the border padding will be added on top of that.
So if you have a row
flex container in a horizontal writing mode, then flex-basis
, inline-size
and width
will all be sizing the width of the flex item content box.
For example, you give a flex item a flex-basis: 100px
and padding: 20px
. You’ll get a content box sized at 100 pixels, and a padding box sized at 140 pixels.
Sizing the border box might feel more intuitive
If you set box-sizing: border-box
on a box, then you’ll get a content box sized at 60 pixels, and a padding box sized at 100 pixels. That’s more in line with our expectation of a box that’s “100 pixels wide”.
The content box can’t have a negative size, which might mess up flex item proportions
The content box can never have a negative size. So if you set box-sizing: border-box
, set flex-basis: 0
, and add some padding, then you’ll end up with a border box that is not 0 pixels.
This is why flex items don’t end up with sizes proportional to their flex-grow
ratios when they have padding and border. It’s because padding and border are fixed, and they take away from the remaining space on a flex line. So the space available for growing is smaller than the full length of the flex line.