Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

180 LESSON 8: Using CSS to Style a Site


Output ▼


I gave the outer <div> a large 40-pixel margin so that you could see how it moves the
borders away from the edges of the browser window. Note also that there’s now space
between the text in the outer <div> and the border. You can also see that the padding
of the outer <div> and the margin of the inner <div> are combined to provide 30 pixels
of whitespace between the border of the outer <div> and the border of the inner <div>.
Finally, it’s important to understand the behavior of the background color. The back-
ground color is applied to the padding, but not to the margin. So, the 15-pixel margin
outside the inner <div> takes on the background color of the outer <div>, and the margin
of the outer <div> takes on the background color of the page.

FIGURE 8.9
Both the inner
<div>and the
outer <div> have
margin and
padding.

Collapsing Margins
In the CSS box model, horizontal margins are never collapsed. (If you put two items
with horizontal margins next to each other, both margins will appear on the page.)
Vertical margins, however, are collapsed. Only the larger of the two vertical margins
is used when two elements with margins are next to each other. For example, if a
<div>with a 40-pixel bottom margin is above a <div> with a 20-pixel top margin,
the margin between the two will be 40 pixels, not 60 pixels.

To center text within a box, the text-align: center; style property is used. The ques-
tion now is this: How do you center a box on the page? In addition to passing units of
measure or a percentage to the margin property, you can set the margin to auto. In the-
ory, this means to set this margin to the same value as the opposite margin. However, if
you set both the left and the right margins to auto, your element will be centered. To do
Free download pdf