Box-sizing CSS Property, The Practical Understanding

Box-sizing CSS Property, The Practical Understanding

·

2 min read

Hello friends,

In this short post we will try to understand the CSS property box-sizing in its simplest term with a very simple analogy I used to understand this property. Before we start My name is Alex Otoo, I am a self-taught web developer and I enjoy sharing what I learn as well as learning from others.

The CSS box-sizing comes to mind whenever we start writing our CSS reset code. The common code we write is mostly by setting the entire document box-sizing to border-box. Like this *{box-sizing: border-box;}

What is box-sizing property?

The box-sizing property simply sets how the total width and height of an element is calculated hence allowing us to include padding and border to the total width and height of elements.

Why is border-boxing mostly preferred? By default, the box-sizing property is set at content-box. This sets the total width of an element to this width + border + padding = total width and height to height + border + padding = total height of an element.
It means when you set the padding and border of an element they are added to the width/height of the element Not as part of the whole width/height.

Screenshot 2021-08-01 at 6.18.08 pm.png

Hmmm, What do you mean? Ok here is where my analogy comes in handy.

Here is how box-sizing by default looks like in my analogy world, So you go to your favourite food outlet for lunch, mine is Taco Bell and I get myself a Cheese Roll-Up for $3.00 and pay with a $5.00 note. I will be expecting a $2.00 change, but they give me back my $5.00 together with my $3.00 worth Cheese Roll-Up. So, I end up getting a total of $8.00 worth of value in my hands.
This mostly leads to unwanted element sizes and a whole lot of confusion. To avoid this, we set box-sizing to border-boxing. border-boxing will ensure that padding and border accounts for the total width/height of an element but not the separate value from the width/height. Using the analogy that will mean, we get $3.00 worth of Cheese Roll-Up and get our expected $2.00 change back to make a total of $5.00 worth of value in our hands. I hope you agree with me that this is how a fair world must operate.

Here are a list of element set to border-box by default by most browsers input elements with type radio, checkbox, reset, button, submit, color, or search. table, button select,

Thank you all. Lets keep sharing.