CSS Box Model — Explained
Let’s see how CSS’s Box Model works before that lets see how the HTML element’s size is calculated after rendering.
Let’s see with an example
If, you notice from the above CSS the width and height are set to 100px but in actual its width and height is 120px. In case if user really wants the actual width precisly to be 100px then you can to reduce the width to 80px. Here, if you notice margin is not calculated as part of actual width.
Here is how the calcuation goes (padding-left: 5px + padding-right: 5px + border-left: 5px + border-right: 5px) minus 100px which is 80px;
which might solve the issue. What if there is requirement to change the reduce/increase the padding later on then we have to do the calculation and make changes to it which is tedious and time consuming.
We have an easy way to overcome this issue by using the box-sizing property of CSS. Here is how it looks like
Here, if you notice we have not modified the width of the HTML element instead we have added box-sizing: border-box CSS property and this is future proofed as well. Even in future/later on if we change the padding or border it wouldn’t have any impact.
You can find the live code here
Let me know your valuable comments.