Each element on a web page is wrapped around by a box. The arrangement of these boxes makes up the layout of the website. Building layouts is a crucial part of front-end development which is what makes understanding the box-model indispensable.
Features of the box:
Each box has padding, margin and border.
Padding: The space between the content and the border.
Margin: The space around the border.
Border: Indicates the dimensions of the box.
Dimensions of the box:
The dimensions of the box are computed as follows:
width of box = width of element + padding-left + padding-right + border-left+ border-right
height of box = height of element + padding-top + padding-bottom + border-top + border-bottom
Take a look at the following CSS for example:
div {
width: 100px;
height: 100px;
padding: 10px;
border: 5px solid red;
margin: 10px;
}
width of the box = width of element (100px) + padding-left(10px) + padding-right(10px) + border-left(5px)+ border-right(5px) = 130px
height of the box = height of element(100px) + padding-top(10px) + padding-bottom(10px) + border-top(5px) + border-bottom(5px) = 130px
Therefore, the dimensions of the box are 130px x 130px.
Notice that while we intended the element to be 100px x 100px, the padding and border added 30px to both width and height. This can make our elements overflow and compete with each other for space, messing up the layout.
Box Sizing:
The solution for this is a CSS property called box-sizing. The default value of box-sizing is set to content-box.
Content-box: Includes width and height of only the element. The padding and the border are not included.
Therefore, padding and border add extra pixels to the element, thus increasing the overall dimensions of the box.
The alternate option is border-box.
Border-box: Includes padding and border. As padding and border are altered, the dimensions of the element are adjusted accordingly, to keep the dimensions of the box fixed.
Let's apply border-box to our previous example.
div {
width: 100px;
height: 100px;
padding: 10px;
border: 5px solid red;
margin: 10px;
box-sizing: border-box;
}
Notice that the dimensions of the box remain 100px x 100px even after adding padding and border. This is achieved by automatically adjusting the dimensions of the element to 70px x 70px, in order to accommodate padding and border.
Tip:
Set the box-sizing to border-box using the universal selector(*), to reset the default box-sizing property of all elements, at the beginning of your stylesheet.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
If this article helped your understanding of the box-model, let me know in the comments!
Top comments (3)
Really nice, I like the illustrations, especially the one comparing content-box and border-box, it's quite clear what is the difference :) Thanks for the post.
Glad you like it, Tanwa :)
Basic, but great explainedππ½