By default, an element’s width and height are computed as follows:
width + padding + border = actual width of the element height + padding + border = actual height of the element
Consequently, when you define the width/height of an element, it frequently appears larger than specified, as the element’s border and padding are added to its specified width/height.
The subsequent illustration displays two <div> elements with identical specified width and height:
The two <div> elements depicted above ultimately have differing sizes in the output (due to the padding specified for div2).
Example
.div1 { width: 300px; height: 100px; border: 1px solid blue; } .div2 { width: 300px; height: 100px; padding: 50px; border: 1px solid red; } |
The box-sizing property resolves this issue.
The box-sizing property enables us to incorporate padding and border dimensions into an element’s overall width and height.
When you apply box-sizing: border-box; to an element, its width and height now encompass padding and border dimensions.
Here is the identical example as previously mentioned, with box-sizing: border-box; applied to both <div> elements:
Example
.div1 { width: 300px; height: 100px; border: 1px solid blue; box-sizing: border-box; } .div2 { width: 300px; height: 100px; padding: 50px; border: 1px solid red; box-sizing: border-box; } |
Given the superior outcomes of utilizing box-sizing: border-box;, numerous developers seek to implement this approach for all elements on their web pages.
The following code guarantees that all elements are sized in this more intuitive manner. While many browsers already employ box-sizing: border-box; for numerous form elements (though not all, hence discrepancies in the appearance of inputs and text areas at width: 100%;), extending this to all elements is both prudent and secure.
Example
* { |