Why do we need box-sizing in CSS?

Short answer: You need box-sizing property in CSS because it determines how the width and height of an element are calculated, including the element’s padding and border.

For example, if you’re building a grid system or a responsive layout, using box-sizing: border-box can help you ensure that your elements are always the same size, even if you add padding or border to them.

Values of the property ( content-box is default):

  • content-box: border and padding are increasing element dimensions
  • padding-box: border is increasing element dimensions
  • border-box: element dimensions are not increased

Example:

 /* Box with content-box */
    .content-box {
      box-sizing: content-box;
      width: 100px;
      height: 100px;
      padding: 20px;
      border: 5px solid rgb(32, 177, 239);
      margin: 20px;
    }

    /* Box with border-box */
    .border-box {
      box-sizing: border-box;
      width: 100px;
      height: 100px;
      padding: 20px;
      border: 5px solid rgb(32, 177, 239);
      margin: 20px;
    }

Explanation:

With box-sizing: content-box, the width and height of the box will only include the content area, not the padding or border. This means that the total width and height of the box will be 150px (100px + 2 * 20px padding + 2 * 5px border).

With box-sizing: border-box, the width and height of the box will include the content, padding, and border. This means that the total width and height of the box will be 100px (the specified width and height), and the padding and border will be added within the box, making the content area smaller.

That’s it!

Leave a Reply

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