CSS Box Model and Box Sizing Explained
If you are a developer writing any kind of CSS, you should know about the box model, and how it relates to the sizing of elements.
Let’s dig in to that right now.
The CSS Box Model
Every HTML element is a box.
That box has 4 different layers:
- Content
- Padding
- Border
- Margin
How those 4 layers are laid out is defined in the box model.
Here’s how it looks:
Since every HTML element is a box, every HTML element is also based on this model.
CSS Box Sizing
Now that you know what the box model is, we can learn about box sizing.
You might think that setting the width of an element to 100px will make that element 100px wide, but that’s not always true, and I’ll tell you why in a second.
Box sizing tells the browser what should be included in the width
and height
that you have defined on your element.
There are two different types of box sizing: content-box
and border-box
.
Content-box
The default value is content-box
. This tells the browser to only include the content area in the specified width and height. Any padding, border and margin will be added on top of that, making the element wider or taller.
Let me give you an example to illustrate.
If you have an element with a width of 100px, padding of 20px, and a border of 2px, the total width of that element will be 100px + 20px + 2px = 122px.
Border-box
With border-box
, the specified width and height of an element will include both the content area, the padding and the border.
If we take the same example as above and change the box sizing to border-box
, the total width of the element would be 100px.
Which one should you use?
Many people, including myself, prefer to use border-box
.
That way, you can add padding and borders without worrying about elements becoming wider or taller than the specified dimensions.
One popular way of setting the box sizing is this way:
html {
box-sizing: border-box;
}
*, ::before, ::after {
box-sizing: inherit;
}
What we’re doing here is setting the box sizing on html
, the root element. Then we tell every element on the page—including pseudo elements—to inherit that box sizing.
Why can’t we just set the box sizing on all elements directly? Well, you could, but the approach above makes it easier to work with elements that need to use content-box
. You can read more about the topic on CSS-Tricks.