CSS Box Sizing


The CSS property called "box-sizing" lets us count the padding and border as part of the overall width and height of an element.


Without the CSS box-sizing Property

Usually, an element's size is determined in the following way by default:

Adding the width, padding, and border of an element together gives you its real or actual width. Similarly, combining the height, padding, and border of an element gives you its real or actual height.

When you specify the width and height of an element, it can often appear larger than what you've actually set. This is because the element's border and padding get added to its specified width and height.

In this picture, you can see two boxes that have been given the same width and height values:

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 have different sizes in the outcome. This happens because div2 has padding defined.

The "box-sizing" property fixes this issue.


With the CSS box-sizing Property

The box-sizing property helps us count the padding and border in the total width and height of an element.

If you use box-sizing: border-box; for an element, it means that the padding and border will be considered when calculating the width and height.

Both divs are the same size now!

Hooray!

Here's a similar example to the one above, but with the addition of box-sizing: border-box; to both <div> elements.

Because using box-sizing: border-box; makes things work much better, many developers want all the parts of their webpages to do this.

The following code makes sure that all elements are sized in a more understandable manner. Some browsers currently apply the box-sizing: border-box; style to certain form elements (though not all), which is why inputs and text areas might appear differently when set to width: 100%.

Using this approach for all elements is a smart and secure choice.


CSS Box Sizing Property

Property Description
box-sizing This code defines how a web page element's size is determined. It decides whether the element's dimensions should consider its padding and borders or not.