Before we begin our discussion about using <div> elements, and how they are used for template and page construction, we must understand an important concept of divs, namely the CSS Box Model. A <div> and indeed all box level elements contain many properties, but it is four of these that are important to our discussion. They are content width, padding, border, and margin.

#content {
   margin: 10px; /* a margin of 10px on each side */
   padding: 2px; /* a padding of 2px on each side */
   border: 1px solid #000000; /* a 1px border on each side */
   width: 100px; /* set the content region to 100px */
}

Before we begin the next step of our discussion, be sure to read the above code example. This is a CSS declaration for a CSS element with an id of #content where we are setting the four properties we mentioned previously. What might you expect the width of our <div> to be? A natural reaction would be to say that it is obviously 100px, because of the width: 100px; line. This would be incorrect however.

To better understand why this is incorrect, consider the example below.

CSS Box Model explained
Image courtesy of w3.org.

By looking at the above example, we see a box level element, and each of the main parts, and how they relate to each other. Working from inside out, we see that there is the actual content, then the padding, then border, and finally margin. A box level element includes all of these within itself, so while our content width is set to 100px, the <div> actually includes all the rest. So, 100px + 20px + 4px + 2px = 126px! (Be sure to consult the comments in the CSS declaration above to see where these values come from) This may take a while to understand, and can lead to a lot of frustration initially.

It is important to understand this concept as you design templates. If you are making a very tight design, and are a pixel or two off, your design may not look at all how you intended it to be. Another thing to keep in mind is that by default a block level elements takes up 100% of the space available to it. As a little twist, if you specify a border, margin, and/or padding, and leave width auto (that is, set no value), the <div> will be width 100%, not 100% + padding + margin + border.

If you run into problems, go back and make sure you are accounting for all elements and all the properties. If you still are still having problems, validate your CSS, validate your XHTML, be sure to check the CSS Quirks Section, and if you are still having problems, consult an online resource, or contact the Web Development Office.

So far we have only addressed width, and ignored height. This is because height is determined largely by content. You can control the height of an element, and we will talk about this more later. For now, let's look at how to create a <div> and how to control it.