We can use the box-sizing property to specify where to assign the fixed sizes – to the content box or to the border box.
It affects the interpretation of all sizing properties, including flex-basis.
box-sizing-content-box
Sizes specified on sizing properties as length-percentage represent the box’s inner sizes.
w3.org
Let’s understand the statement. Sizing properties are width, height, min-width, min-height, max-width, and max-height. inner size is the content-box size of a box. (FYI: outer size is the margin-box size of a box).
It’s easier to understand that statement now.
👉 When we define the height, width etc, using percentages it will stay inside the inner sizes excluding the margins/border/padding.
The sizes are are applied to the content box. The padding and border of the box are laid out and drawn outside the specified width and height.
box-sizing: border-box
Sizes specified on sizing properties as length-percentage represent the box’s visible sizes, including the borders/padding (but not margin). The sizes are applied to the border box.
👉 The padding and border of the box are laid out and drawn inside the specified width and height.
The content box sized to fill the remaining space, floored at zero.
The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified length-percentage.
As the content width and height cannot be negative, this computation is floored at zero.
Values affected by box-sizing include both raw length-percentage values and those used in functional notations such as fit-content().
In contrast, non-quantitative values such as auto and min-content are not influenced by the box-sizing property (unless otherwise specified).
w3.org
Look at this examples
The inner size can’t be less than zero, so if the padding + border is greater than the specified border box size, the box will end up larger than specified.
In this following example, the content-box size will floor at 0px so the border-box size ends up at 120px, even though width: 100px is specified for the border box:
Let’s look at another example.
We can include the padding and border in an element’s total width and height using box-sizing property, by setting it as box-sizing: border-box.
In this following examples, you can see the two versions of two div elements (with and without padding). As soon as you specify the box-sizing: border-box, it will make the div elements of a same size.
Credit: w3.org
box box-sizing examples property