Introduction Into Box-model and Box-sizing in CSS

June 15, 2015 css | Comments

Every HTML element is represented as box and has four edges: margin, border, padding, content. Web developers tools in Chrome has nice feature to display it in graphical way:

"Box model - webdeveloper tools"

Before box-sizing property was released in CSS we had to calculate width or hight value when wanted to use paddings or borders in HTML elements and avoid changing it’s sizes. eg:

before use paddings:

1
2
3
4
.element {
  width: 100px;
  height: 100px;
}

after use paddings and/or border:

1
2
3
4
5
6
.element {
  width: 89px;
  height: 89px;
  padding: 10px;
  border: 1px solid #000;
}

width and height property needs to be less of the padding 10px and 1px of border to not increase original size of element. But if we use box-sizing property which can be content-box or border-box or initial or inherit we can have better dimensions control of box:

Content-box (default value)

If we use it then to calculate width and height of element will be taken only min/max/width and min/max/height properties. Paddings, margins or borders are not included. What does it mean? Take a quick look at below example:

1
2
3
4
.element {
  width: 100px;
  height: 100px;
}

after use paddings, border and box-sizing:

1
2
3
4
5
6
7
.element {
  width: 100px;
  height: 100px;
  padding: 10px;
  border: 1px solid #000;
  box-sizing: content-box;
}

element still has 111px of height and width (100px + 10px + 1px).

Border-box (default value)

If we use it then to calculate width and height of element will be taken min/max/width and min/max/height properties, paddings and borders. Margins are not included. Example:

1
2
3
4
.element {
  width: 100px;
  height: 100px;
}

after use paddings and border and box-sizing:

1
2
3
4
5
6
7
.element {
  width: 100px;
  height: 100px;
  padding: 10px;
  border: 1px solid #000;
  box-sizing: border-box;
}

element does not change it’s sizes. Has still 100px width and height. But content inside has less dimensions 89px x 89px (100px - 10px - 1px).

Simply yes ?

Initial

Just set property to its default value.

Inherit

Just iherits from parent element. Not worth to describe.

Compability

Chrome browser Internet Explorer browser Firefox browser Safari browser Opera browser
>=10.0
4.0 -webkit-
>=8.0 >= 29.0
2.0 -moz-
>= 5.1
3.2 -webkit-
9.5

Summary

Using box-sizing always depends on project needs, application HTML structure and so on. But if you don’t want bear in mind additional calculations of height or width and avoid changing size after using borders or paddings I recommend to set box-sizing into border-box.

Thats, all. I know that in web is a lot of similar articles about box sizing but I hope mine is a little bit different and more helpful. If you want to leave some comments go ahead!

Comments