O'Reilly logo

CSS Cookbook, 3rd Edition by Christopher Schmitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Understanding the Box Model

Problem

You want to better understand the box model and how margins, borders, and padding work around content.

Solution

Every block-level element, such as a p or div element, contains a top, right, bottom, and left edge. These sides of a block element are composed of three layers surrounding the content, as shown in Figure 2-20.

Box model viewed straight on and off to the side

Figure 2-20. Box model viewed straight on and off to the side

Therefore, each block element contains four sections:

Content

Actual content such as text, images, Java applets, and other objects. The content area is in the middle of the box.

Padding

Surrounds the content area.

Border

The next-outer layer that surrounds the padding and makes up the box border.

Margin

The transparent box that begins at the edge of the border and expands beyond.

The default margin value is 0, which lines up with the edge of the border. A border with a value of 0 lines up with the padding edge.

Obviously, a padding value of 0 lies flush against the content. Values above 0 expand the boxes.

Discussion

For a mental image of the box model, picture a cardboard box on the floor.

Looking down at the box you see its four sides: top, right, bottom, and left. The box can be as big or as small as you want because you can modify the size of the box through the height and width properties:

div {
 height: 150px;
 width: 150px;
}

Add books into the box until you fill the box with books: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required