With the margin-top, margin-right, margin-bottom, and margin-left properties, you can specify a margin for one side of an element. Margin size may be specified in any of the accepted units of length. Negative values are permitted. Figure 19-4 shows examples of adding margins to individual sides of an element. Note that the dotted lines are a device to point out the outer edge of the margin and would not display in the browser.

    h1 { margin-top: 3px; }
    h1 { margin-right: 20px; }
    h1 { margin-bottom: 3px; }
    h1 { margin-left: 20px; }

Percentage values are also permitted, but be aware that percentages are calculated based on the width of the parent element. If the parent element gets narrower (perhaps as the result of the browser window resizing) the margins on all sides of the child elements will be recalculated.

Margins may also be set using the keyword auto, which allows the user agent to fill in the amount of margin necessary to fit or fill the containing block.

Individual margin settings

Figure 19-4. Individual margin settings

Tip

The proper way to horizontally center an element in CSS is to set the left and right margins to auto. This technique (as well as the workaround required for Internet Explorer in anything but Standards mode) is addressed in Chapter 24.

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.