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 toborder-box
, which means that the width of the.box
element will include the padding and border. - We're then setting a width of
300px
, adding20px
of padding, a1px
black border, and10px
of margin. - Without the
box-sizing
property set toborder-box
, the total width of the element would be300px
(the content width), plus40px
(the padding), plus2px
(the border), plus20px
(the left and right margins), for a total width of362px
. - With box-sizing set to
border-box
, the total width of the element is300px
, 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
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 of300px
includes the20px
padding and1px
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 of300px
does not include the20px
padding and1px
border. - The total width of the box, including the padding, border, and margin, is
362px
.