CSS box-sizing
property specifies whether the padding and border of an element should be included in its total width and height or not.
Without CSS box sizing
By default, the padding and border of the element are not included in its total width and height. Therefore, the actual size of the element may be larger than the size we have set using the width and height property.
For example, suppose, we have a <div>
element having a width of 300px and height of 100px. As shown below.
Now, suppose, we want to add a padding of 50px each side to this <div>
element keeping the width and height same as earlier(width=300px, height=100px). Now see how does it looks:
You can easily notice that the second <div>
is bigger than the first one, although, we kept the width and height exactly the same for both the <div>
elements. This happened because, by default, the width and height property sets the width and height of the content of the element only, not its total width and height.
Try out the example below to see the implementation:
Example:
.div1{ width: 300px; height: 100px; border: 1px solid blue; } .div2{ width: 300px; height: 100px; padding: 50px; border: 1px solid red; }
With CSS box sizing
The above problem can easily be fixed using the box-sizing
property.
If we set the box-sizing
to border-box
, the padding and border of the element will be included in its total width and height.
In this situation, the width and height property sets the actual width and height of the element, not the width and height of the content only. Therefore, the actual size of the element never exceeds the size set by the width and height property.
Therefore, both the <div>
elements will be of same size(Width=300px and Height=100px) now.
Try out the below example to see the implementation:
Example:
.div1{ width: 300px; height: 100px; border: 1px solid blue; } .div2{ width: 300px; height: 100px; padding: 50px; border: 1px solid red; box-sizing: border-box; }