WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

CSS3 Box Sizing


CSS3 Box Sizing

The CSS3 box-sizing property allows us to include the padding and border in an element's total width and height.


Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Numbers followed by -webkit- or -moz- specify the first version that worked with a prefix.

Property
box-sizing 10.0
4.0 -webkit-
12.0 8.0 29.0
2.0 -moz-
5.1
3.1 -webkit-
9.5

Without the CSS3 box-sizing Property

Usethis calculation for width and height

width + padding + border = actual width of an element
height + padding + border = actual height of an element

The element 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:

width is 250px and height is 120px.

width is also 250px and height is 100px.

The two <div> elements above end up with different sizes in the result (because div2 has a padding specified):

Example

.div1 {
    width: 250px;
    height: 120px;
    border: 1px solid blue;
}

.div2 {
    width: 250px;
    height: 120px;
    padding: 60px;
    border: 3px solid red;
}
Try it yourself »

So, for a long time web developers have specified a smaller width value than they wanted, because they had to subtract out the padding and borders.

With CSS3, the box-sizing property solves this problem.


With the CSS3 box-sizing Property

The CSS3 box-sizing property allows us to include the padding and border in an element total width and height.

If you set box-sizing: border-box; on an element padding and border are included in the width and height:

This both div are same size

Final

above in HTML , with box-sizing: border-box; added to both <div> elements:

Example

.div1 {
    width: 250px;
    height: 120px;
    border: 1px solid blue;
    box-sizing: border-box;
}

.div2 {
    width: 250px;
    height: 120px;
    padding: 30px;
    border: 1px solid red;
    box-sizing: border-box;
}
Try it yourself »

final results box-sizing: border-box; is so much better, Many user .

The code below ensures that all elements are sized in this more intuitive way. Many browsers already use box-sizing: border-box; for many form elements (but not all - which is why inputs and textareas look different at width: 100%;).

Applying this to all elements is safe and wise:

Example

* {
    box-sizing: border-box;
}
Try it yourself »