Unboxing the box model

Unboxing the box model

What is the box model? Differences between Content-box vs Border-box.

Whenever we start building a website, we can immediately see that all elements are displayed as a box. Why is this? πŸ€” The browser represents them as rectangles according to the CSS box model.

Every box element (like a div) has different properties that can be customised like its width, height, padding (space between content and borders, similar to the space between a photo and its frame), borders (lines around the content) and margins (space out of the box or div in this case).

boxmodel.png

By default, the browser renders a box model called content-box, meaning, an element's width and height will be altered by the padding and border values we add. Therefore, we can calculate the total width or height of an element by summing up all properties values:

total width = width + padding + border

However, the content box is a bit tricky as it can get us into trouble with dimensional issues. That is why there is another box-sizing property called border-box, which tells the browser to not modify an element's width whenever we add some extra padding and border.

In this case, the total width already includes padding and border values, which makes the content adjust automatically.

Let's have a look at an example of both models together to see the size differences.

Both divs or boxes have the same properties except from box-sizing. On the one hand, the first div has the content-box property, where the total width is:

width (400px) + padding (20px x 2) + border (5px x 2) = 450px

On the other hand, the second div has the border-box property, where the total width is 350px, meaning, the borders and padding don't add any extra value.

width (400px) - padding (20px x 2) - border (5px x 2) = 350px

In order to avoid dimensional issues, whenever you style a website, it is recommended to start like this

startoncss.png

That's all folks! 🐱

Β