Skip to main content

Introduction to CSS Box Sizing

CSS Box Sizing

The box-sizing property in CSS is used to control the box model used by an element. The box model determines how an element's width and height are calculated, including any padding, borders, and margins.

There are two values for the box-sizing property:

  • content-box: This is the default value and means that an element's width and height only include its content. Any padding, borders, or margins are added to the width and height.

  • border-box: This value includes an element's padding and border in its width and height, so any padding and border are taken into account when calculating an element's total size. The margin is still added to the total size.

As an example:

.box {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 1px solid black;
margin: 10px;
}

In this example:

  • We're setting the box-sizing property to border-box, which means that the width of the .box element will include the padding and border.
  • We're then setting a width of 300px, adding 20px of padding, a 1px black border, and 10px of margin.
  • Without the box-sizing property set to border-box, the total width of the element would be 300px (the content width), plus 40px (the padding), plus 2px (the border), plus 20px (the left and right margins), for a total width of 362px.
  • With box-sizing set to border-box, the total width of the element is 300px, and the padding and border are included in this width.

Here is an example that demonstrates the difference between box-sizing: border-box and box-sizing: content-box:

Editor

Loading...

In this example:

  • We have two boxes with the same width, padding, border, and margin, but different box-sizing values.

In first example:

  • The first box has box-sizing: border-box, which means that its width of 300px includes the 20px padding and 1px border.
  • The total width of the box, including the padding, border, and margin, is 342px.

In second example:

  • The second box has box-sizing: content-box, which means that its width of 300px does not include the 20px padding and 1px border.
  • The total width of the box, including the padding, border, and margin, is 362px.