My favourite CSS techniques are the ones that are tiny but have a huge impact. Step up the global box-sizing technique, which Paul Irish published in 2012. Chris Coyier declared February 1st, International box-sizing awareness day, which I also celebrate every year.
This is how I use the technique in my “modern reset”:
- Code language
- css
*, *::before, *::after { box-sizing: border-box; }
This is slightly different to Paul’s inherit
pattern. I prefer to be more explicit with this sort of thing. Either way works though, so I wouldn’t recommend losing any sleep over it.
What does this technique change?permalink
I’ll let past me explain from the Learn CSS course:
Alongside an understanding of how user agent styles affect each box, you also need to understand
box-sizing
, which tells our box how to calculate its box size. By default, all elements have the following user agent style:box-sizing: content-box;
.Having
content-box
as the value ofbox-sizing
means that when you set dimensions, such as awidth
andheight
, they will be applied to the content box. If you then setpadding
andborder
, these values will be added to the content box’s size.
This default box-sizing
behaviour creates a confusing situation when dimensions are applied to an element. Using border-box
however makes everything much more predictable. I’ve had the attitude for years now that content-box
should be the default, but it is what it is.
See the Pen Box sizing demo by piccalilli (@piccalilli) on CodePen.
Wrapping uppermalink
Of all the fantastic capabilities and techniques that have arrived in CSS in the last 12 years, this is still the greatest of all time, in my opinion.
Go forth and build predictably sized boxes 🫡