Box Model in CSS

The Web Book

Width+Borders
The line above is 250px wide (width+left and right borders).
The total width of this element is also 250px (width+borders).
Width+Padding+Borders

The line above is 250px wide (width+left and right borders).
The total width of this element is now 270px (width+padding+borders).

CSS Box Model Example Code

HTML CODE .................................................................... <!DOCTYPE html> <html> <body> <div class="c1"></div> <br> <div class="c2"> The line above is 250px wide (width+left and right borders).<br> The total width of this element is also 250px (width+borders). </div> </body> </html> CSS CODE ............................................................................ div.c1 {width:240px; border:5px solid gray; border-color:#ff0000 #0000ff;} div.c2 {width:240px; padding:0px; border:5px solid gray; margin:0px;}

The total width of an element is calculated like this:
Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The total height of an element is calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

So, as per the first equation, the width of the above element is calculated as under:
240px (width)+ 0px (left and right padding)+ 10px (left and right border)+ 0px (left and right margin) = 250px

Change the value of padding to 10px. This change adds a space of 10px (between content and surrounding border) on all four sides of the content resulting in expansion of width from the allowed 250px space, as shown in the second illustration above.

Considering the equation mentioned above, the browser calculated the width of the element like this:
240px (width)+ 20px (left and right padding)+ 10px (left and right border) = 270px

Back