Skip to main content

CSS Box Sizing

By SamK
0
0 recommends
Topic(s)

The box-sizing property in CSS enables us to include the padding and border within an element's total width and height.

Without the CSS box-sizing Property

By default, the width and height of an element are calculated as follows:

width + padding + border = total width of the element
height + padding + border = total height of the element

This means that when you set the padding and/or border of an element, it often appears larger than the specified size, because the border and padding are added to the element's defined width and height.

The following illustration demonstrates two <div> elements with the same specified width and height.

.div-one {
  width: 200px;
  height: 100px;
  background-color: skyblue;
}
.div-two {
  width: 200px;
  height: 100px;
  background-color: skyblue;  
  padding: 15px;
  border: 2px solid green;
}

The two <div> elements above end up with different sizes in the result because .div-two has specified padding and border as shown in the below preview.

Without CSS Box Sizing

The box-sizing property addresses this issue.

With the CSS box-sizing Property

The box-sizing property lets us include padding and border within an element's total width and height.

When you apply box-sizing: border-box; to an element, the padding and border are included in the element's specified width and height.

In this example, we have applied box-sizing: border-box; to .div-two element, which makes it appear the same size as .div-one element, which has no border or padding.  

.div-one {
  width: 200px;
  height: 100px;
  background-color: skyblue;
}
.div-two {
  width: 200px;
  height: 100px;
  background-color: skyblue;
  padding: 15px;
  border: 2px solid green;
  box-sizing: border-box;
}

With CSS Box Sizing

Since box-sizing: border-box; yields more predictable results, many developers prefer to apply it to all elements on web pages.

The following code will apply this property to all elements on the page, which is both safe and advisable.

* {
  box-sizing: border-box;
}

Questions & Answers