- Published on
Understanding CSS Box Size and `box-sizing`
- Authors
- Name
- hwahyeon
Why are the box sizes different?
.div1 {
border: 10px solid pink;
width: 300px;
height: 200px;
}
.div2 {
border: 10px solid lightblue;
width: 300px;
height: 200px;
padding: 40px;
}
div1
div2
The .div1
and .div2
elements have the same width
and height
values, but their actual sizes differ. This is because width
and height
in CSS only account for the content area by default, excluding borders and padding.
Actual Size Calculations:
.div1:
- Width: 300px + 10px(border) × 2 = 320px
- Height: 200px + 10px(border) × 2 = 220px
.div2
:- Width: 300px + 10px(border) × 2 + 40px(padding) × 2 = 400px
- Height: 200px + 10px(border) × 2 + 40px(padding) × 2 = 300px
Without including borders and padding in your calculations, it’s challenging to precisely set the desired size.
box-sizing
CSS3 introduced the box-sizing
property to solve this problem. By default, it uses the content-box
model, but you can change it to border-box
. With border-box
, the width
and height
include borders and padding.
.div1 {
box-sizing: border-box;
border: 10px solid pink;
width: 300px;
height: 200px;
}
.div2 {
box-sizing: border-box;
border: 10px solid lightblue;
width: 300px;
height: 200px;
padding: 40px;
}
div1
div2
Both .div1
and .div2
now have an exact size of 300px × 200px, including borders and padding. No extra calculations are required.
Applying to All Elements
Using box-sizing: border-box;
is so convenient that most projects apply it to all elements by default. This ensures all element sizes include borders and padding, making layout management much easier.
* {
box-sizing: border-box;
}
Notes and Considerations
- Parent-Child Relationships:
The box-sizing
property only affects how an element's size is calculated. It does not directly impact the sizes of parent or child elements.
- Not Inherited:
The box-sizing
property does not inherit its value by default. To ensure consistent behavior across all elements, you need to explicitly apply it to all elements using the *
selector or define it at the root level.
- Browser Support:
Modern browsers fully support box-sizing
. However, if you need to support older browsers (e.g., IE7 or earlier), consider alternative styles or polyfills.