Last Updated: February 25, 2016
·
535
· geekytime

CSS - common-sense padding and borders

By default, the CSS box model adds border and padding to the OUTSIDE of your element. Yeah, I know it seems silly, but it's how the CSS box model is designed to work. This can be highly irritating. Especially as we move into responsive designs that use ems and percents for these kinds of values.

  • But fear not! Box-model salvation is close at hand! *

The 'box-sizing' property in CSS lets you specify how you want borders and padding to be added. The stinky default value is 'content-box'. Yuck.

If you change 'box-sizing' to 'border-box', then the border and padding will be magically squeezed * inside * the content box where they belong, and only the margins will extend outside. Nice.

If you are a coward who is afraid of new things, you can use this property selectively:

.myElement {
    box-sizing: border-box;
}

Or, if you'd like to inject all kinds of awesome directly into your CSS, you can just apply it universally:

* {
   box-sizing: border-box;
}