Box Model: Basics

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:

.outer
.inner

We'll now add 1em of margin or padding, in various combinations, to each element and observe the results.

Example 0: no margins or padding

By default, a div has no margins or padding, so no spacing is present:

This is the content area

Note how the inner div takes up all the space and 'hides' the outer div's light grey background colour.

Example 1: outer div padding

#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:

This is the content area

Example 2: inner div padding

#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.

This is the content area

Example 3: outer margin

#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.

This is the content area

Example 4: inner margin

#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.

This is the content area

Example 5: inner and outer padding

#outer6,
#inner6 { padding: 1em; }

Padding on both elements gives each space to breathe, between its content and its border:

This is the content area

Example 6: inner and outer margin

#outer7,
#inner7 { margin: 1em; }

Margins on both elements create additional space around their borders:

This is the content area

Example 7: outer margin, inner padding

#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:

This is the content area

Example 8: outer padding, inner margin

#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:

This is the content area

Tweet

Comments

Leave a comment