Difference Between border-box and content-box in CSS

difference between border-box and content-box

The CSS box-sizing property allows us to include or exclude the padding and border in an element’s total width and height. It has two values border-box and content-box. In this article, we will learn the differences between them.

box-sizing: content-box

This is the default value. It adds the padding and border to the total width and height of the elements. So the total width and height become like this:

Total height = height + padding + border
Total width = width + padding + border

Let’s look at an example.

HTML code:

  <body>
    <div></div>
    <p>SemicolonSpace</p>
  </body>

CSS code:

div {
    width: 300px;
    height: 30px;
    background-color: blueviolet;
}
p {
    box-sizing: content-box;
    width: 300px;
    border: 1px solid red;
}

Output:

css box-sizing content-box

There are two elements (div and p) with width 300px. The div is just for reference. Now, let’s increase the border size of the p element to 10px.

p {
    box-sizing: content-box;
    width: 300px;
    border: 10px solid red;
}

Output:

content-box css

As you can see in the output, the total width and height of the element are changed. The new width value is 320px (300 + 10 + 10).

box-sizing content-box

So, when you set box-sizing: content-box on an element, the border and padding are added to the total width and height.

box-sizing: border-box

If you use border-box, padding and border are included in the total width and height. This means that total width and height remain unchanged.

Let’s take the above code and set box-sizing: border-box on the p element.

p {
    box-sizing: border-box;
    width: 300px;
    border: 10px solid red;
}

Output:

border-box in css

Now, the total width remains 300px. The border is included in the total width.

box-sizing border-box

So, with the border-box, when you add padding and border, the total width and height of the element are not affected.

Leave a Comment