Grouping with <DIV>

Sometimes we need to group a bunch of elements together as a unit for purposes of CSS placement or styling.

A div has no visible representation itself, but is simply a grouping construct so that you can apply a CSS rule to the group as a whole.

The Problem

Consider this problem: we'd like to draw a single green border that surrounds all three paragraphs below.

<p>I like to eat cookies!</p>
<p>Baseball season starts in April.</p>
<p>Chicago is cold in the winter.</p>

The following CSS doesn't quite work. It draws three borders instead of one (can you explain why?):

p { border: solid 3px green; padding: 12px; }

The Solution

First, we group the elements together with a div and apply a class for our CSS rule:

<div class="framed">
  <p>I like to eat cookies!</p>
  <p>Baseball season starts in April.</p>
  <p>Chicago is cold in the winter.</p>
</div>

Next, we rewrite our CSS rule as a class definition:

.framed { border: solid 3px green; padding: 12px; }

Presto!