CSS Box Sizing Property
Styling with CSS is fun until you scratch your head when unexpected styling behavior starts to surface. Most of the time, web developers encounter overflowing content after applying style properties to an element. This is a “shoot yourself in the foot” moment where an element starts to overflow when setting such style properties. Though, there is a CSS property that can be utilized to control or mitigate overflowing elements.
CSS Box Model
Before proceeding, it is important to know that the CSS box model is a rectangular representation of an element with four parts, namely the content, padding, border and margin area. The model plays an important role in the calculation of width and height in relation to adjustments to the box-sizing, padding and border properties.
What is the box-sizing property?
The box sizing property controls how the width and height of an element are calculated when a box model property such as padding or border is applied. The style property can accept either “content-box” or “border-box” as its value.
Box-sizing using content-box
The default box-sizing behavior uses content-box. An example below depicts a simple parent-child element structure as an initial layout.
The parent container has a fixed width of 250px
and a fixed height of 200px
. The child element inherits the parent width with a fixed height of 100px
as its initial box size. The simple layout below looks fine, right?
What if we apply a padding of 20px
to the child element? It will overflow outside its parent. Ever wondered why? This is because the padding box is not part of the fixed width and height and is added instead on top of the child element’s initial box size.
As a result, the box size now has a bigger dimension of 290px
for the width and 140px
for the height due to the padding box changes, yet the content box size stayed the same as shown in the blue highlighted region above.
Box-sizing using border-box
Changing the default box-sizing behavior to border-box resolves the overflowing issue with the child element.
The reason why is how the added padding is allocated to the box size. Instead of adding the padding on top of the box size, it will be distributed and be part of the fixed width and height.
As a result, the box size stayed the same, yet it shrinks the content box size, as shown in the blue highlighted region. The content box has a deducted dimension of 210px
for the width and 60px
for the height. The remaining 80px
are allocated for the padding box just outside the content box.
Eureka Moment
Now that we know how the box-sizing property works, we can utilize the knowledge gained on the reasons behind overflowing or unexpected element sizing issues. The amount of time that can be saved from debugging and frustration by knowing the right behavior and properties in CSS is great, which leads to better developer velocity.