CSS Box Sizing

CSS Box Sizing

CSS box-sizing property allows us to include the padding (fill) and border in the total width and height of the element.

Suppose the CSS box-sizing property is not specified

By default, the width and height of the element are calculated as follows:

  • width + padding + border = actual width of the element
  • height + padding + border = actual height of the element

This means: When you set the width/height of an element, the element usually looks larger than you set (because the element's border and padding have been added to the specified width/height of the element).

The following figure shows two <div> elements with the same specified width and height:

This div is smaller
(width is 300px, height is 100px).
This div is larger
(width is also 300px, height is 100px).

The two <div> elements above have different sizes in the final result (because div2 specifies padding):

Example

.div1 {
  width: 300px;
  height: 100px;
  border: 1px solid blue; 
}
.div2 {
  width: 300px;
  height: 100px;
  padding: 50px;
  border: 1px solid red;
}

Try It Yourself

box-sizing property solves this problem.

If you use the CSS box-sizing property

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

If the element has the box-sizing: border-box;Then the width and height will include the padding and border:

Now both divs are the same size!
Hooray!

This example is the same as the previous one, both <div> elements have set box-sizing: border-box;:

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;
}

Try It Yourself

Due to the use box-sizing: border-box; which is so good that many developers wish all elements on the page could work in this way.

The following code ensures that all elements can be adjusted in this more intuitive way. Many browsers have already been using the effect on many form elements in this way, box-sizing: border-box;(but not all - that's why input and textarea look different when width: 100%;).

It is safe and wise to apply it to all elements:

Example

* {
  box-sizing: border-box;
}

Try It Yourself

CSS Box Sizing Property

Property Description
box-sizing Define the calculation method for the width and height of elements: whether they should include padding and borders.