CSS Box Sizing
What is CSS Box sizing Property?
Before starting with CSS box-sizing, let's first understand what issue occurs if we don't use this property.
Without CSS box-sizing
If we don't include box-sizing property, then the box model works like below as default:
It means if we create a box of some specific height and width and then add padding and border to it, it will look wider than the actual width.
To deal with this issue, developers need to adjust the values for height and width to give space for border and padding. Let's understand it with an example:
Example: Let's create two div with same height and width, but with different border and padding.
In the above code, we have created two divs of the same size. In the first div, we have not included padding, whereas, in the second, we added it.
It will generate the output as:
As we can see from the above output, that we got two div with different sizes. While we have specified the same sizes of both the div, but the second appears bigger than the first.
This is the main issue that occurs in the CSS box model. This issue can be resolved with the help of box-sizing property.
With CSS box-sizing property
The above issue can be resolved by using the CSS box-sizing property. Now we will use the same code as above, but will also include box-sizing property to it.
In the above code, we have used two divs of the same height and width and also used the box-sizing property for each div.
As we can see in the above output, we got both div with the same width.
Syntax of box-sizing property is given as:
Value: CSS box-sizing property has two values, which are border-box and content box. These are given as:
In this, the dimension of value is calculated as below:
In the above code, we have used the content-box value of the box-sizing property.
The browser will display a box of size 500, in which 480px wide area for width will be included.
In this, the width and height are calculated by including content, border, and padding. But it does not include the margin.
The dimensions of the element are calculated as:
In the above code, we have used the border-box value of the box-sizing property.