CSS Box Sizing
Learning outcomes:
- What is
box-sizing
in CSS - How it affects dimensions
What is box sizing
A fairly recent property, box-sizing
is used to control which bounding box of an element is given dimensions to. In other words it controls which box gets re-sized upon change of dimensions.
The values of this property and their purposes are very easy to understand and implement in real as you will see below.
content-box
is the default and applies dimensions to the content box.border-box
applies dimensions to the border box.
If you don't know what are bounding boxes in CSS and their three types, consider reading the chapter on Bounding Boxes.
As we said in the previous chapter that box-sizing
can affect the final dimensions of an HTML element we will now show how can this be possible.
Content Box
The content-box
value is the default value for box-sizing
and won't really amaze you that much as would the next one in this couple.
Anyways, to define it; this value causes any dimension given on a given element to be applied to its content-box. Following we give a custom width and height to the div
element, both of which will be the width and height of the content box.
div {
width: 200px;
padding: 40px;
border: 10px solid black;
box-sizing: content-box; /* default */
}
The width of each box is given as follows:
- The width of the content box is 200px.
- The width of the border box and the final width is 300px
Border Box
The border-box
value causes any dimension given on a given element to be applied to its border-box.
Although, for you at this point it won't feel that amazing, when box-sizing
came with the border-box
value, it solved many layout problems that previously required more work to be done the same way.
Consider the same example as the one above but this time using box-sizing: border-box
this time:
div {
width: 200px;
padding: 40px;
border: 10px solid black;
box-sizing: border-box;
}
The width of each box, in this case, is given as follows:
- The width of the content box is 100px.
- The width of the border box, which is also the final width, is 200px. This is the value of the
width
property - and similarly whatever value we give to it will be the width of this wholediv
container.
In conclusion, box sizing is an important concept to understand in modern CSS as it can solve some common layout problems very easily and quickly.
Spread the word
Think that the content was awesome? Share it with your friends!
Join the community
Can't understand something related to the content? Get help from the community.