This site is mobile accessible. Press the "Tap Here" button to use a smaller font-size.
Smartphone icons created by Freepik - Flaticon
The CSS box-sizing property allows us to include the padding and border in an element's total width and height.
By default, the width and height of an element is calculated like this:
This means: When you set the width/height of an element, the element often appears bigger than you have set (because the element's border and padding are added to the element's specified width/height). The following illustration shows two <div> elements with the same specified width and height:
This div is smaller (width is 300px and height is 100px).
This div is bigger (width is also 300px and height is 100px).
The two <div> elements above end up with different sizes in the result (because div2 has a padding specified):
.div1 { width: 300px; height: 100px; border: 1px solid blue; } .div2 { width: 300px; height: 100px; padding: 50px; border: 1px solid red; }
The box-sizing property solves this problem.
The
property allows us to include the padding and border in an element's total width and height. If you set on an element, padding and border are included in the width and height:Both divs are the same size now!
Hooray!
Here is the same example as above, with
added to both <div> elements:.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; }
Since the result of using the
is so much better, many developers want all elements on their pages to work this way. The code below ensures that all elements are sized in this more intuitive way. Many browsers already use for many form elements (but not all - which is why inputs and text areas look different at width: 100%;). Applying this to all elements is safe and wise:* { box-sizing: border-box; }
Property | Description |
---|---|
box-sizing | Defines how the width and height of an element are calculated: should they include padding and borders, or not |