box-sizing property
The box-sizing property allows you
to change the method element
dimensions are calculated.
By default, adding
padding
expands the element: if we set a
width
to 100px and a
padding-left
to 20px, then the actual width
of the element will be 120px.
And if we also set a
border-left
to 10px, then the actual width of
the element will become 130px. That
is, padding and border expand
the block (both in width and height). This
behavior can be changed
using box-sizing.
Syntax
selector {
box-sizing: content-box | border-box;
}
Values
| Value | Description |
|---|---|
content-box |
Both padding and border expand a block.
|
border-box |
Neither padding nor border expand the block. |
Default value: content-box.
Example . Default behavior
Now both blocks have the same height and width,
but the second block has padding set,
while the first block does not. Look how
different their sizes are:
<div id="elem1">elem1</div>
<div id="elem2">elem2</div>
#elem1 {
width: 300px;
height: 100px;
margin-bottom: 10px;
background: #f1f1f1;
}
#elem2 {
padding: 50px;
width: 300px;
height: 100px;
background: #f1f1f1;
}
:
Example . Default behavior
Now both blocks have the same height and width,
but the second block has a border set to 10px,
while the first does not. Look how different
their sizes are:
<div id="elem1">elem1</div>
<div id="elem2">elem2</div>
#elem1 {
width: 300px;
height: 100px;
background: #f1f1f1;
}
#elem2 {
border: 10px solid black;
width: 300px;
height: 100px;
background: #f1f1f1;
}
:
Example . Default behavior
Now the second block has both
padding and a border
of 10px:
<div id="elem1">elem1</div>
<div id="elem2">elem2</div>
#elem1 {
width: 300px;
height: 100px;
background: #f1f1f1;
}
#elem2 {
padding: 50px;
border: 20px solid black;
width: 300px;
height: 100px;
background: #f1f1f1;
}
:
Example . The border-box value
Let's add the border-box value to the
second element for the box-sizing
property. Now the sizes of both the first
and second elements will be the same:
<div id="elem1">elem1</div>
<div id="elem2">elem2</div>
#elem1 {
width: 300px;
height: 100px;
background: #f1f1f1;
}
#elem2 {
box-sizing: border-box;
padding: 50px;
border: 10px solid black;
width: 300px;
height: 100px;
background: #f1f1f1;
}
:
See also
-
the
outlineproperty
that makes a border not expand an element