Setting the width and height of block elements

Width and height are fairly easy concepts but remember that you set the width and height of the content. Padding, margins and borders all get added on.

Here is an example with a few settings for a DIV. Copy this into a new, blank HTML file called boxmodel.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />            
        <title>A demonstration of width and height styling for a DIV</title>
        
        <style>
            #div1 {                   
            
                width:100px;
                height: 200px;
                
border-width:2px; border-color:black; border-style:solid; padding:2px; margin:10px; } </style> </head> <body> <div id="div1"> <p>Hi</p> </div> </body> </html>

Ignore the border-width and following lines. They will be explained soon and are there to make this example look better.

The important lines for this example are the width and height. They set the width and height of the DIV in pixels (the elements which make up any display).

Carefully read and understand the STYLE section and the DIV which it styles (in the BODY).

View the page in a browser resizing the browser window. Then replace the width and height lines with these:

            
width:50%;
height:25%;
        

Save and view in a browser. Resize the browser window and see the behaviour of the DIV box. Percentage sizes have a very different effect to fixed sizes.

If you do not set the height and width of a DIV (or other block element) it will fill the whole width of the page and normally the height will come from the content. If you use absolute positioning (explained soon) the DIV will have zero height and width unless you set it (the content still shows but it overflows the box it is in). When creating a page it is worth setting a temporary background colour for each DIV just to check it is where you expected and the size you expected.

submit to reddit Delicious Tweet