If you look at the left and right sides of the pages in this book, you'll notice that there is whitespace that appears between the paragraphs of text and the edge of the pages; you probably know this space as the margin of the book. Style sheet margins allow you to add empty space around the outside of the rectangular area for an element on a web page. Following are the style properties for setting margins:
You can specify margins using any of the individual margin properties, or with the single margin property. If you decide to set a margin as a percentage, keep in mind that the percentage is calculated based on the size of the entire page, not the size of the element. So if you set the margin-left property to 25%, the left margin of the element will end up being 25% of the width of the entire page. The following code shows how to set the top and bottom margins for one of the colors in the Color Blocks sample page that you've been working with throughout this lesson: div.two { background-color:green; margin-top:5px; margin-bottom:20px; } In this example, the top margin is set to 5 pixels, and the bottom margin is set to 20 pixels. The results of this code are shown in Figure 14.6. Figure 14.6. The Color Blocks sample page is displayed using a style sheet that sets top and bottom margins for one of the colors.This figure shows how the top and bottom margins appear above and below the second div element. Keep in mind that these margins don't encroach on the content area of any of the colorsthey all maintain their original size. In other words, the margins appear around the elements. If you want to set all the margins for a style rule, you'll probably want to simplify the code and use the margin property. This property is somewhat flexible in that it offers three different approaches to specifying the margins for a style rule. These approaches vary based on how many values you use when setting the property:
Following is an example of how you would set the vertical margins (top/bottom) to 5 pixels and the horizontal margins (left/right) to 10% for a style rule: margin:5px 10%; In this code, the top and bottom margins are both set to 5 pixels, and the left and right margins are both set to 10%. Of course, if you wanted to be a little clearer, you could achieve the same effect with the following setting: margin:5px 10% 5px 10%; |