Приглашаем посетить
Экономика (economics.niv.ru)

Recipe 2.1 Eliminating Page Margins

Previous Page Table of Contents Next Page

Recipe 2.1 Eliminating Page Margins

Problem

You want to get rid of the whitespace around the edges of a web page and between the browser chrome and the contents of the page, as shown in Figure 2-1.

Figure 2-1. Page margins visible as the whitespace around the edges of a web page
figs/csscb_0201.gif


Solution

Set the value of the margin and padding properties for the html and body elements to 0:

html, body {

 margin: 0;

 padding: 0;

 position: absolute;

 top: 0;

 left: 0;

}

Discussion

Setting the margin and padding properties of the body element to 0 helps create a full-bleed effect—in other words, it eliminates the whitespace around a web page (the units in this case don't matter). And setting the position to absolute and the values for top and left to 0 helps remove the body margins in Netscape Navigator 4.

However, depending on the content of the web page, the margin and padding properties might not be all you need to change to get a full-bleed effect. Default properties on other elements can have unexpected side effects when attempting to change the page margin For example, if h1 is the body element's first child element, some unintended whitespace will appear above the headline and below the top of the browser's viewport. Figure 2-2 shows this undesired effect; the background color of the headings and paragraphs is gray so that you can more clearly see the effect.

Figure 2-2. Whitespace above the heading and below the top of the browser's viewport
figs/csscb_0202.gif


To ensure the full-bleed effect in this situation you should set the margin and padding of the offending element (in this case, h1, h2, h3) to 0 as well as the body. This sets all the sides of the element's padding to 0. If that setup isn't possible (for example, you need to have a value at the bottom padding or margin), set the margin-top and padding-top values to 0 to maintain the full-bleed effect:

body {

 margin: 0;

 padding: 0;

} 

h1, h2, h3 {

 margin-top: 0;

 padding-top: 0;

 background-color: #666;

}

p {

 background-color: #999;

}

As you can see in Figure 2-3, this accomplishes the full-bleed effect. Notice how the gray background color of the first heading now touches the top of the browser's viewport.

Figure 2-3. Whitespace removed above the heading
figs/csscb_0203.gif


See Also

Recipe 7.2 for writing one-column layouts by setting the margin and padding properties to a value other than 0.

    Previous Page Table of Contents Next Page