Controlling the ZOrder Position

Using styles, you can also control the z-order position of an element. All visible elements in a browser have a z-order value. Elements with higher values appear above elements with lower values. In standard HTML, the position of an element in the HTML stream determines its z-order position. In other words, elements toward the end of the HTML stream will appear above elements earlier in the stream. CSS supports a z-index attribute that controls the relative z-order position of each element. For example, to plot the text "Hello World" on top of the bike image element, you can write a page such as that seen in Listing 2.9.

Listing 2.9: Controlling the Z-Order Position (ch2-20.htm)

<div style="position:absolute; left:100; top:100; z-index:0">

<img src="images/bike.gif" border=1> </div>

<div style="position:absolute; left:100; top:100; z-index:1">

<b><font size="5" color="blue">Hello World</font></b> </div> </BODY> </HTML>

The z-index value of 1 forces the browser to plot the text on top of the image, which has a z-index value of 0. Now, you may not be impressed, but I sure was when I saw this for the first time, because until that point, you had to use table cell background images to plot text on top of an image.

CSS styles support relative positioning as well, in which the browser determines an element's position relative to the position of its parent. You can express both absolute and relative positions in either pixels or percentages, using either positive or negative values. I'm a big fan of using percentages to specify positions whenever possible. If you use percentages, you isolate your page elements from dependence on the client's screen resolution. Also, the positions of display elements remain constant relative to the screen, even when the browser changes size.

For example, in Listing 2.10, the <span> tag containing the text "I'm Here!" plots above and to the left of its parent <div> tag.

Listing 2.10: Absolute and Relative Positioning (ch2-2l.htm)

<div style="position:absolute; left:100; top:100; z-index:0">

<img src="images/bike.gif" border="1" WIDTH="227" HEIGHT="17 9"> </div>

<div style="position:absolute; left:100; top:100; z-index:1"> <b><font size="5" color="blue">Hello World</font></b> <span style="position:relative; left:-100%; top:-100%; z-index:2"><b><font size="5" color="red"> I'm Here!</font></b></span>

Figure 2.19 shows how Listing 2.10 plots in a browser.

ffc £>* fU.riiM rsfc

- — J* JJ .'J

■ ■J-'WH J -. i" ■

U* h* ] r.Ur i>3Z J1 Mi ■

jj .kjk ■

^J bM ft'VVNWH

Figure 2.19: Absolute and relative positioning (ch2-21.htm)

Was this article helpful?

0 0

Post a comment