Slide 5.15: CSS box model
Slide 5.17: CSS border
Home

CSS Box Model (Cont.)


Width and Height of an Element
When you specify the width and height properties of an element with CSS, you are just setting the width and height of the content area. To know the full size of the element, you must also add the padding, border and margin. The total width of an element should be 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 should be calculated like this:
 Total element height = height + top padding + bottom padding
  + top border + bottom border + top margin + bottom margin
The total width of the element in the example below is 300px:
   width:250px;              padding:10px;
   border:5px solid gray;    margin:10px;
because
 300px = 250px + 10px + 10px + 5px + 5px + 10px + 10px
Browsers Compatibility Issue
If you tested the previous example in Internet Explorer, you saw that the total width was not exactly 300px. IE includes padding and border in the width, when the width property is set, unless a DOCTYPE is declared. To fix this problem, just add a DOCTYPE to the code:

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   <html>
    <head>
     <style type="text/css">
      div.ex { width:250px; padding:10px;
       border:5px solid gray; margin:10px;
      }
     </style>
    </head>


Demonstration
The following demonstration shows how the script of HTML and CSS is displayed on the Web: