CSS Box Sizing
CSS Box Sizing
We can include the padding and border in the total width and height of an element by using the CSS box-sizing property.
Without the CSS box-sizing Property
An element’s default calculation of width and height looks like this:
width plus padding plus border equals an element’s real width.
Actual element height is equal to height plus padding plus border.
This indicates that when you set an element’s width or height, the element frequently seems larger than you have provided because padding and the element’s border are added to the width or height that you have specified.
Two <div> elements with the same specified width and height are displayed in the following illustration:
Because div2 has a padding provided, the two <div> elements above end up having different sizes in the result:
Example
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
}
This issue is resolved by the box-sizing attribute.
With the CSS box-sizing Property
We can include the padding and border in the total width and height of an element by using the box-sizing property.
When you set padding and border to an element with box-sizing: border-box;, they are included in the width and height:
Because box-sizing: border-box; yields such superior results, many developers desire that all elements on their pages function in this manner.
This more logical sizing of all items is ensured by the code below. For many form components (but not all, which is why inputs and text areas look different at width: 100%;), many browsers already employ box-sizing: border-box;.
Using this for every element is prudent and safe:
Example
* {
box-sizing: border-box;
}
CSS Box Sizing Property
Property | Description |
---|---|
box-sizing | Defines how the width and height of an element are calculated: should they include padding and borders, or not |