box-sizing
When we declare a block-size and/or inline-size (or width and height), those values are for the size of the content box.
When we add padding, border, and margin, those are all being added on top of our declared sizes.
That sounds logical, but when we start creating layouts it can actually be really annoying, because when we have padding on an element, it feels like that it should be a part of the size of that element, since visually it’s part of the box.
See the Pen box sizing by Kevin (@kevinpowell) on CodePen.
The inline-size: 100% on the paragraph looks like that means it should take up 100% of the section, but instead, the content box is 100%, and then we add the padding and border on top of that size, and it overflows out the side.
There is a way to change this behavior though, with the box-sizing property. The default value is content-box, but we can change that to border-box, so that both padding and borders are included in our declared size.
Try adding that declaration to the paragraph, and suddenly, things start working as you’d expect them to.
When we change the box-sizing to border-box, we’re now saying the sizes that we declare on the element include the content box, plus the padding, plus the border.
It simply makes things much more intuitive to work with, so much so that it’s become one of the most universally used lines of CSS.
The problem is, you generally want to change that for all elements, and not on a case by case basis.
To do that, we can use the universal selector, which is *.
Using the * selector selects every element in your document.
So, we can do this:
* { box-sizing: border-box;}This is one of the most common lines of CSS, though I will say that I’ve recently been rethinking using it.
In the old days of the web, we had to declare sizes for everything, and this made everything much easier to work with. These days, with tools like Flexbox and Grid, it’s much less common to run into issues with box sizing.
I will say there is probably no harm in using it, but I wouldn’t say it’s a mandatory addition to every CSS file like I used to suggest.
The main thing I’d say is, pick whether you want to use it or not, and pay attention to when an element isn’t sizing the way you’d like it to, and switch the box-sizing either to content-box or border-box to fix the issue.