mydomain
No ADS
No ADS

CSS box-sizing Tutorial with Examples

  1. CSS box-sizing:content-box
  2. CSS box-sizing:border-box
  3. CSS box-sizing:padding-box (!)

1. CSS box-sizing:content-box

No ADS
CSS Box Modal is a container, created from many components, including content, paddings, margins, borders. Below is the illustration of a Box Model:
CSS {box-sizing:content-box}
CSS box-sizing has the default value of content-box, which means that the default element is a "Context-Box".
In case the element is a "Content-Box",CSS width/height will be the width and height of the rectangle containing the contents of the element, which means that when an element is established padding or border (or both), it will make the element bigger.
box-model-example.html
<div style="border: 1px solid gray;width:200px;height:100px;">
     border: 1px solid gray; <br/>
     width:200px; <br/>
     height:100px;
</div>
<div style="margin: 20px;padding:30px; border: 10px solid gray;width:200px;height:100px;">
    margin: 20px; <br />
    padding:30px;   <br/>
    border: 10px solid gray;  <br/>
    width:200px;  <br/>
    height:100px;
</div>
The actual size of an "Content-Box" element is calculated by the formula:
realWidth = contentWidth + cssBorderWidthLeft + cssBorderWidthRight + cssPaddingLeft + cssPaddingRight

realHeight = contentHeight + cssBorderWidthTop + cssBorderWidthBottom + cssPaddingTop + cssPaddingBottom
Of which:
// box-sizing:content-box (Default):
// We have:
contentWidth = cssWidth
contentHeight = cssHeight

2. CSS box-sizing:border-box

No ADS
Sometimes you want to establish border, padding for an element and do not want to increase the element size. This is possible if you use CSS box-sizing:border-box. This element will then be considered as a "Border-Box".
If an element is a "Border-Box", CSS width/height will be "width / height" of the rectangle including both padding and borders.
box-sizing-border-box.html
<!DOCTYPE html>
<html>

<head>
    <title>CSS box-sizing</title>
    <meta charset="UTF-8"/>
    <style>
         .my-box  {
            box-sizing:border-box;
            width:250px;
            height:120px;
            margin: 20px;
            padding:30px;
            border: 10px solid gray;
         }
    </style>
</head>
<body>
    <h3>CSS {box-sizing:border-box;}</h3>
    <div class = "my-box">
        box-sizing:border-box; <br/>
        width:250px;  <br/>
        height:120px;  <br/>
        margin: 20px; <br/>
        padding:30px;   <br/>
        border: 10px solid gray;
    </div>
</body>
</html>

3. CSS box-sizing:padding-box (!)

Note: Most browsers do not support CSS box-sizing:padding-box (or no longer support it).
If an element is established CSS box-sizing:padding-box, it will be considered as a "Padding-Box". CSS width/height is then the width and height of the rectangle that contains padding, but not includes borders.
No ADS
No ADS