Setting CSS
width
and
height
properties doesn't guarantee that
the element will become the given
size. Let's look at examples.
Example
Now the dimensions of the element are the same as given:
<div id="elem">
text
</div>
#elem {
width: 200px;
height: 200px;
margin: 50px auto;
background: #CFF5BF;
}
:
Example
Now let's set the
padding
property to the element. As a result, the
actual width of the element will become
larger and expand by the given padding
value:
<div id="elem">
text
</div>
#elem {
padding: 25px;
width: 200px;
height: 200px;
margin: 50px auto;
background: #CFF5BF;
}
:
Example
Having a border also expands the element:
<div id="elem">
text
</div>
#elem {
width: 200px;
height: 200px;
margin: 50px auto;
background: #CFF5BF;
border: 20px solid #F0D7A1;
}
:
Example
box-sizing
property allows you to change the
behavior described above. You can
make sure that neither the padding
nor the border expands the element.
To do this, this property must be
set to border-box
value:
<div id="elem">
text
</div>
#elem {
box-sizing: border-box;
padding: 20px;
width: 200px;
height: 200px;
margin: 50px auto;
background: #CFF5BF;
border: 20px solid #F0D7A1;
}
:
Importance of the described
From the JavaScript point of view, the
described situation is not very
convenient. After all, it turns out
that after reading the value of the
width
property, we cannot at
all be sure that the element will
be exactly this width.