Skip to content
FLAVIO COPES
flaviocopes.com

CSS box-sizing: border-box

By

Learn how the CSS box-sizing border-box value makes width and height include padding and border, so element sizing finally behaves the way you expect.

~~~

By default, if you set a width (or height) on the element, that is going to be applied to the content area.

This does not include the padding, border, and margin, which are added on top.

For example, I set this CSS on a p element:

p {
  width: 100px;
  padding: 10px;
  border: 10px solid black;
  margin: 10px;
}

and here’s what’s applied by the browser:

Default behavior

You can change this behavior by setting the box-sizing property. If you set that to border-box, width and height calculation include the padding and the border.

Here’s what it means on the previous example:

p {
  box-sizing: border-box;
  width: 100px;
  padding: 10px;
  border: 10px solid black;
  margin: 10px;
}

With box-sizing border-box

The border box is now 100 pixels wide. Inside it, the content box is 60 pixels wide: 100 - 20 pixels of horizontal padding minus 20 pixels of horizontal border.

The margin is still outside the declared width, so this example occupies 120 pixels of horizontal layout space when both margins are included.

This property is a small change but has a big impact in how you calculate your elements dimensions.

Demo on Codepen

You can apply it to every element on the page with this rule:

*,
*::before,
*::after {
  box-sizing: border-box;
}
Tagged: CSS · All topics
~~~

Related posts about css: