CSS Tips & Tricks: Using Border Box

Video Guide on using CSS Border Box.

Today we’ll go over a very easy css hack that will let you define the size of elements and not have it be affected by border and padding values.

Here is the code:

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

Here is what the code does. The first line of CSS applies box-sizing to be border-box. The second line applies it across the entire website by having all the following elements inherit the border-box value while giving you the freedom to override it, if you want to, for a specific element.

So what does Border-box do exactly? Whatever dimensions you set for an element are not affected by padding and border values.

Here is a comparison between content-box and border-box.

As you can see, the padding and border values do not adjust the dimensions of a border-box. This is very handy when you want to define dimensions exactly and not have them be affected. It makes adjusting the layout of your site much more straight forward.

Here is an excellent article by Paul Irish if you to learn more about border-box: https://www.paulirish.com/2012/box-sizing-border-box-ftw/

Here is the mdn page covering box-sizing if you would like more information: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

Hope that helps! Leave a comment down below with your favorite css hacks! Hope you guys are staying safe and sane out there and catch you guys next time!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s