header image

Code Snippets

Set CSS `box-sizing` Property Globally

| Last updated:
*,
*::before,
*::after {
  box-sizing: border-box;
}

Change the default CSS box-sizing property value to help developer intuition

The default value for the CSS box-sizing property is content-box. Therefore, by default, properties such as border-width`` andpadding``` are not included in the content sizing of a selected element. This can lead to confusion when defining an element's width and height.

For example for the given element:

.box {
  width: 100px;
  padding: 20px 20px;
  border: 3px solid teal;
}

The element's display size with default box-sizing: content-box will be:

  • width => 146px
  • content (inner) width => 100px

Whereas, size with box-sizing: border-box applied, e.g.

.box {
  box-sizing: border-box;
}

The element's display size will be:

  • width => 100px
  • content (inner) width => 54px

Normalize

To prevent the above confusion, it is common to use the above snippet globally in the site's author stylesheet to normalize this behaviour, helping developer intuition.