Select Page
CSS Box-Sizing
CSS Box-Sizing

This is probably the most important concept for any web designer working with CSS. And it also seems confusing in beginning but is very simple to understand once we try it practically.

Content-Box

The default value of ‘box-sizing’ is ‘content-box’. This means the total width of an element would be its width (if defined by you) + its border size + its padding.


Example:

Open example in a full window – https://demos.webdevpuneet.com/css/box-sizing/content-box.html

Source Code

<div class="content-box">
    The default value of ‘box-sizing’ is ‘content-box’. This means the total width of an element would be its width (if defined by you) +it’s border size + padding.
</div>

<style>
  .content-box{
    width: 300px;
    background: #cecece;
    border:15px solid #999;
    padding:25px;
    box-sizing:content-box;
  }
</style>

Problem with Content-Box

During complex layout structuring, this becomes extremely difficult to handle as the actual width keeps on increasing with an increase in padding and border.

Border-Box

Border-box is the other value we can give to the elements to make them expand inwards instead of expanding outwards, making things simple to understand and implement. This means element width remains what it was assigned and only the inner area is compressed when we increase its padding and border size.

Example:

Open example in a full window – https://demos.webdevpuneet.com/css/box-sizing/border-box.html

Source Code

<div class="border-box">
  Width remains what it was assigned and only the inner content area is compressed when we increase its padding and border size.
</div>
<style>
  .border-box{
    width: 300px;
    background: #cecece;
    border:15px solid #999;
    padding:25px;
    box-sizing:border-box;
  }
</style>

Difference

Open in a full window – https://demos.webdevpuneet.com/css/box-sizing/difference.html

Add this line of code at the beginning of your CSS file to make everything easy and predictable with border-box. This sets all elements in a document to border-box.

*{box-sizing:border-box;}

Nowadays almost all Front-end/UI/CSS frameworks like Bootstrap and Reset CSS uses ‘box-sizing:border-box;’ to make web development easier for web designers.

Related Queries

  • Why is my div getting out of a container?
  • Why my element size is showing more than what I have assigned to it?
  • What is the default value of box-sizing in CSS?
  • Why use border-box for CSS box-sizing?
  • How to make HTML element’s width fixed in spite of border and paddings?