CSS Box Sizing

By default, margin, padding & border adds together to calculate the total width or height of an element. 

The actual width of an element is calculated as –

width + margin + padding + border-width = Total width of element

Similarly, by default, the actual height of an element is calculated as –

height + margin + padding + border-width = Total height of element
css box sizing without border box.

Example without box-sizing: border-box

section {
 background:skyblue;
 border:3px solid black;
 width:200px;
 height:200px;
 padding:10px;
 margin:10px;
}

CSS box-sizing: border-box

The example shown above concludes that the actual width/height of the element is greater than or equal to the width/height you set for the element so the element which you define looks bigger than the length you set by default.

Now, if you want to set the length of your element exactly the same size as you defined, you should code box-sizing:border-box for that element.

Here, the actual width of the element will be equal to the width of the element.

css_box_sizing

width = Total width of element

So, the actual content area will shrink in this case but the total width will be same as the width set for the element which also includes margin, padding and border. In other way, it is like –

1. width of content Area + padding + margin + border-width = Total width
2. As, width of content Area = width - (padding + margin + border-width)
3. width - (padding + margin + border-width) + padding + margin + border-width = Total width

Hence, width = Total width 

The Syntax of Box sizing border box:
box-sizing: border-box;

Example of Box sizing with border box

.secA {
 box-sizing:border-box;
 background:skyblue;
 border:3px solid black;
 width:100px;
 height:100px;
 margin:4px;
}

.secB {
 box-sizing:border-box;
 background:skyblue;
 border:3px solid black;
 width:100px;
 height:100px;
 padding:30px;
 margin:4px;
}

.secC {
 background:skyblue;
 border:3px solid black;
 width:100px;
 height:100px;
 padding:30px;
 margin:4px;
}

CSS Box sizing content box

If you do not code the box-sizing property, it will take box-sizing:content-box by default.

The Syntax of Box sizing content box:
box-sizing: content-box;

Example of Box sizing content box

.box1 {
  box-sizing:content-box;
  background:hotpink;
  border:3px solid black;
  width:200px;
  height:200px;
  margin:4px;
}

Box sizing inherit

The box-sizing:inherit will acquire the box-sizing property from its parent element

The Syntax of Box sizing inherit:
box-sizing:inherit;

Example of Box sizing inherit

.div1 {
 background:skyblue;
 width:300px;
 height:400px;
 padding:10px;
 margin:10px;
 box-sizing:border-box
}

.divA{
 background:navy;
 width:150px;
 height:150px;
 padding:10px;
 margin:10px;
 box-sizing:inherit
}

.divB{
 background:hotpink;
 width:150px;
 height:150px;
 padding:10px;
 margin:10px;
 box-sizing:inherit;
}

Tutorials for all brains!