My Development Notes


What is box-sizing : border-box in CSS?


Introduction

This property specifies the behaviour of the width and height of a container, more specifically a div. To understand this property you have to use it on more than one div elements which stack on top of each other, or, on div tags which are in a parent-child hierarchy.

Explanation with examples

Example 1 (without border box)

Let’s say you have a parent div and inside it, you have two child divs in HTML like so :

<div class="container">
      <div class="box-a">
        <h1>This is a box</h1>
        <p>hjdjdkdk kdkkdkk dkdkdkkk kdkkdk</p>
      </div>
      <div class="box-b">
        <h1>This is another box</h1>
        <p>djdkkde dkjkldb kldkjkkl dldklkld.</p>
      </div>
</div>

Now let’s style our CSS file without using box-sizing : border-box property :

.box-a {
  width: 600px;
  height: 200px;
  background-color: aqua;
  padding: 10px;
  border: 5px solid black;
}

.box-b {
  width: 600px;
  height: 200px;
  background-color: red;
}

This will be the result :

You can clearly see in the above image that the aqua box becomes slightly bigger than the red box after you’ve added padding and border in your CSS. This is because you haven’t used the border-box property yet.

Example 2 (with border box)

Let’s now style our CSS file using box-sizing : border-box property :

div {
  box-sizing: border-box;
}

.box-a {
  width: 600px;
  height: 200px;
  background-color: aqua;
  padding: 10px;
  border: 5px solid black;
}

.box-b {
  width: 600px;
  height: 200px;
  background-color: red;
}

Now, this is going to be the result :

In the image above you can see that both the aqua box and the red box now aligns perfectly to the grid on all sides. The aqua box does not fall off to the right side like in the previous example.

This is because even if we’ve added a padding of 10px and a border of 5px to the aqua box, it does not grow outside the boundaries which is already set by us at 600px X 200px. Rather it takes space from inside the div and adjusts itself inside, accordingly.

Note: Always use this property inside div element selector and not inside class selectors in CSS to make it work.

Why is it used so often?

This property is basically used to align containers perfectly without getting into any trouble especially if you’re wanting to give a border or padding to your container without expanding it outwards.

However, it does not always work under certain complex situations. You have to mix and match and play with it to see if it works for you.


Leave a Reply

Your email address will not be published. Required fields are marked *