Creating a Box in CSS
One of the beauties of CSS is being able to create a box — or container — of information. The placement of the box depends on its relationship with surrounding elements and parent containers. Let's focus on how to create a basic box.
When I say "box," think about a sales page with testimonials. Those testimonials are enclosed in a box set apart from the rest of the content — often with a distinct background color or border. Let's set one of those up.
Starting with a div Tag
A box in HTML begins with a <div> tag. Along with the div, you specify either an id or a class:
- id — used only once on a page (like the header or footer)
- class — can be used multiple times (like a repeating testimonial box)
Since we want multiple testimonials, we'll use a class. Class names always begin with a period in CSS.
The CSS
.testimonial {
line-height: 20px;
background-color: #FFC;
padding: 20px;
width: 400px;
border: outset #CCC;
}
Walking through each property:
- line-height: Space between lines. Increasing it makes the text feel spacious and readable.
- background-color: Sets the box apart visually.
#FFCis shorthand for#FFFFCC— a light yellow. - padding: Space between the content and the edges of the box.
- width: Without a width, a div fills its parent container by default.
- border: Draws a visible edge. Other options:
dotted,dashed,solid,double,groove,ridge,inset,outset.
The HTML
<div class="testimonial">
"Working with Carma completely transformed our website." — James T.
</div>
This is just the beginning. Each box interacts with surrounding content, and boxes can be nested inside other boxes to build more complex layouts. See Seeing the Boxes for the next step.