CSS box-sizing

The box-sizing property in CSS allows you to control how the sizing of an element is calculated. By default, when you set the width and height of an element, these dimensions do not include padding or borders. This can sometimes lead to unexpected layouts, especially when working with responsive designs.

By using the box-sizing property, you can specify whether an element's width and height should include padding and borders. There are two possible values for the box-sizing property:

Let's see an example to understand how box-sizing works:

Result:
This is a box with content-box sizing.

In the example above, we have a div element with a width of 200 pixels, padding of 20 pixels, and a border of 2 pixels. The box-sizing property is set to content-box. Notice how the total width of the element is calculated as:

Width 200px (specified width)
Padding 20px (applied padding)
Border 2px (applied border)
Total Width 222px

Now, let's see the same example but with the box-sizing property set to border-box:

Result:
This is a box with border-box sizing.

In this case, the total width of the element is calculated by including the padding and border:

Width 200px (specified width)
Padding 20px (applied padding)
Border 2px (applied border)
Total Width 200px

As you can see, the total width of the element remains 200 pixels when using border-box as the value for box-sizing. This can be very useful when creating responsive layouts or dealing with box models in CSS.