Introducing the box model and how various configurations of padding and margin affect final layout.
Throughout this example, two boxes are consistently generated by a pair of elements: one div nested inside another. The inner div contains a small amount of sample text. Here's the basic markup:
<div class="outer">
<div class="inner">
This is the content area
</div>
</div>
Each div has been given a uniquely coloured 2 pixel border, and a uniquely coloured background, like so:
.outer { border: 2px solid #CEE14B; background-color: #EEEEEC; }
.inner { border: 2px solid #AD7FA8; background-color: #D3D7CF; }
In addition, each box has been given a line-height of 1 to clearly delineate the content area:
.outer, .inner { line-height: 1; }
Here's how each box is rendered, by default:
We'll now add 1em of margin or padding, in various combinations, to each element and observe the results.
By default, a div has no margins or padding, so no spacing is present:
Note how the inner div takes up all the space and 'hides' the outer div's light grey background colour.
#outer { padding: 1em; }
The addition of padding to the outer div creates spacing between the two borders. Note how the outer div's background becomes visible:
#inner { padding: 1em; }
The two borders revert to clinging right next to each other, but the content area now has some room to breathe, that space lying between the text and inner border.
#outer { margin: 1em; }
Note that there is now a visible 'indent' either side of the entire block of markup and its overall size is, therefore, reduced.
#inner { margin: 1em; }
The inner div is now pushed away from its container, creating space between the two borders. Note how this is exactly the same as example #1.
#outer6,
#inner6 { padding: 1em; }
Padding on both elements gives each space to breathe, between its content and its border:
#outer7,
#inner7 { margin: 1em; }
Margins on both elements create additional space around their borders:
#outer8 { margin: 1em; }
#inner8 { padding: 1em; }
With a margin on the outer box, and padding on the inner one, no space exists between the two, but the content area has room to breathe:
#outer9 { padding: 1em; }
#inner9 { margin: 1em; }
Padding on the outer box and margin on the inner visually combine to create a total amount of 2em space between the two borders: