HTML and CSS

Using Margins

Margins are commonly styled to control the space between elements. You'll have noticed that there's always a certain amount of space, by default, around content displayed in web browsers (visible in Figure 11-1). This can be controlled by changing the margin values in the body element (see Example 11-1).

Example 11-1. Setting margin values for the body element
body {font: 14px Verdana, Arial, Helvetica, sans-serif; color: white; background-color:
 black; margin-top: 0; margin-left: 0; border: 2px solid white;}
h1 {font-size: 24px; color: orange;}
h2 {font: italic 20px Georgia, Times, serif; color: #999; text-indent: 15px;}

You'll see that I have no length value such as px or em after my 0. That's because a 0 value requires no length; the meaning is implicit.

By setting the top and left margins to 0 in the body, the entire body element shifts, along with its children elements (see Figure 11-3).

Figure 11-3. Zeroing the body margins to the top and leftnotice the white border surrounding the body element and how it's flush to the top and left of the viewport.

Check out Figure 11-3 and notice how all the children elements are now flush left, with the exception of the h2, which has a text-indent property set to 15 pixels. But the H1 and paragraph elements, both children of the body with no other identified margins, are flush left and flush top. Or are they? What's the space between the h1 and the outline of the body element? Although the element is obviously flush top, the H1 is not. This is because Mozilla browsers expect a top margin value of 0 for the first element if you want it to be flush with the containing element's top margin. In Internet Explorer, this expectation is ignored and the same style results in the h1 also being flush left and top.

In Example 11-2, I created styles to even more dramatically demonstrate the use of margins with elements, including zeroing out the H1 element.

Example 11-2. Setting a range of margins and values to demonstrate their use
body {font: 14px Verdana, Arial, Helvetica, sans-serif; color: white; background-color:
 black; margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; border: 2px solid
 white;}
h1 {font-size: 24px; color: orange; margin-top: 0; margin-right: 100px; border: 2px solid
 green;}
h2 {font: italic 20px Georgia, Times, serif; color: #999; text-indent: 15px;}
p {margin-left: 100px; margin-top: 5px; margin-bottom: 0; border: 2px solid yellow;}

Figure 11-4 shows how the margins are applied. I've slipped some borders in there to help visualize the margins. You'll learn more about borders later this tutorial.

Figure 11-4. Applying margins to a range of elements including the body, h1, and paragraph elements.
by BrainBellupdated
Advertisement: