Box Sizing

Css Box Sizing property allow us to choose choose border-box or content-box property while using width or height. By default in css, width and height given is applicable to content inside. For overall width and width, we use inspect tool which shows border-box.

Box Sizing values

Box Sizing Example

Content Box Border Box

Content Width : 320, Height: 200

Border Box Width : 340, Height: 220



<style>
  *{ margin:0;}
  .box{ 
    width:320px; 
    height:200px; 
    background:#ccc; 
    padding:10px; 
    box-sizing: content-box 
  }
</style>
box sizing border box and content box
Box Sizing Border Box Vs Content Box


Box-sizing

box-sizing use
content-box Box-sizing content-box consider width equals to content width. Adding border and padding can increase size of box.
border-box Box-sizing border-box consider width equals to total border box. Adding border and padding will not change size of box.

Content Box

content-box

Box-sizing content-box is default value for <div> tag. By adding border and padding to a div with fixed width can change overall width ( border box) of div. For exp, if width is 300px, padding is 10px and border is 5px, then content width is 300px, but overall width (border-box) will be 330px by adding padding and border with width.

content width: 300px
border-box width: 330px


.col{
    box-sizing:content-box;
    width:300px;
    borer:5px solid;
    padding:10px;
}		

          

Note: content-box is default value of box-sizing of div tag.


Border Box

border-box

Css box-sizing border-box was first used in IE Model. But Other browsers were following W3C spec, i.e. content-box. But in CSS3, we can use same border-box model.

Box sizing Border-box include padding and border of an element within. For exp, if width is 300px, padding is 10px and border is 5px, then content width is 270px, but overall width (border-box) will be 300px. Means content width will reduce to maintain border-box.

Only <button> elements default box-sizing is border-box.

border-box width: 300px
content-box: 270px

              
.col{
    box-sizing:border-box;
    width:300px;
    borer:5px solid;
    padding:10px;
}				
            
          

Recommended Way

For modern layouts, use box-sizing: border-box in universal selector, i.e * . We can also use box-sizing: border-box in ::before and :after pseudo selectors as their default box sizing is content-box.


*, ::before, ::after{
      margin:0;
      box-sizing:border-box;
}

Note: box-sizing:border-box is supported in html5 supported browsers, IE 8 and onwards.