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:
content-box
: This is the default value. The width and height of the element only include the content, not the padding or border.border-box
: The width and height of the element include any padding or border that is applied to the element.
Let's see an example to understand how box-sizing
works:
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
:
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.