Box-Sizing Those Border-Box
Today i learned something interesting when it comes to creating layouts in CSS. When creating a layout with a defined width, padding and border your computed width is not what you originally defined as width on your css.
Your computed width is actually width + padding + border you defined in your css file. This becomes a problem if you wanted to create a box that it's 200px wide and when you see your rendered layout it's actually wider since padding and border were added to your defined width.
When creating layouts, the default box model the browser uses is the box-sizing property with the content-box value. If you wanted your computed width to be exactly what you set, you would have to use the box-sizing property with border-box set as it's value. You can set your document to follow the 'box-sizing : border-box' model with this code at the beginning of your CSS document:
/* apply a natural box layout model to all elements */ *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; }
When using border-box value the computed width equals to the content + padding + border. For example:
* { box-sizing: border-box; } .box { width: 200px; padding: 20px; border: 20px; }
The computer width for the code above will equal to 200px wide with padding and border applied. This means your content will be around 140px wide.
if we use the default box model example:
* { box-sizing: content-box; } .box { width: 200px; padding: 20px; border: 20px;
The computed width for the code will equal to 260px wide since your content is defined at 200px wide and both padding and border are added to your total computed width.
In conclusion if you want to declare a width that won't change when adding padding and border, make sure to use the box-sizing property with the border-box value and this will ensure that the final rendered box has the declared width, and any border and padding is cut inside the box.