Boxing - Boxing with CSS, Part I: The Theory - HTML with Style
Boxing with CSS, Part I: The Theory
CSS supposes that a document is displayed in various boxes. You can have boxes within another box, but the basic building block of a rendered document is a box.
A box consists firstly of the content, that is, the stuff it actually displays. A box can, optionally, have a border and a background. A border is a decorative line around the box's contents, and the background is simply a backdrop to the box.
The content of a box is at the center of the box. Around the content is an area called the padding, which is the space between the content and the border. The border is around the padding. And around the border is the margin, which is the space between the box and other boxes around it. Figure 1 should illustrate this pretty clearly.
Figure 1: The Box Model
The background of a box is shown behind the content and the padding only. The margins are always transparent. So, a box with a green background and a blue border would be displayed as shown in Figure 2.
Figure 2: Displaying a Box
A box's margin, border or padding can be set to 0, in which case they are not displayed. The width of the margin, border or padding can be different in the top, bottom, left or right sides of the box. The box in figure three has a zero-width left and right border, zero padding on all sides, and a larger margin on the bottom than on the other three sides.
Figure 3: Another Box
You may have wondered why you haven't seen any of this in your documents so far. The answer is that since the default border width for most elements is zero on all sides, and since the default background on most elements is transparent, the visual effect is something like the one displayed in figure 4 (the grey line between the margin and padding is only meant to show the boundary; it is not actually displayed).
Figure 4: A Typical Box
So even though the margin and padding are there, they are both transparent, and most of the time they are also set to 0, so you only get the content occupying the whole box. Now let's take a look at what the relationship between elements and boxes is, as well as how you put boxes together.