13.2 Connecting a Positioned Element to a Body Element
NN 6, IE 4
Create a positioning context with a relative-positioned container around the primary element, and embed an absolute-positioned element within the container. The following code binds an absolute-positioned photo copyright image to the photo image:
<div style="position:relative; margin-left:20%"> <img src="kitty.jpg" height="511" width="383" style="border:4px groove darkred" alt="My Kitty" /> <img src="photoCopyright.jpg" style="position:absolute; top:519px; left:263px" alt="Copyright 2003 Snaps McGraw" /> </div>
The result appears in Figure 13-1. The relative-positioned container has a percentage value for its margin, so its precise horizontal position varies with the width of the browser window. But no matter where the photo image appears on the page, the copyright image will appear immediately below it and flush right in the following supported browsers: Internet Explorer 4 or later (except 5.0 for Windows) and Netscape 6 or later.
In the Solution, the coordinates of the absolute-positioned element need to be adjusted for each inline image because the coordinates depend on the size of the image. The 0,0 point of the coordinate system is determined by the location of the first element encased in the relative-positioned div element. Although the main image has a height of 511 pixels, the image has a four-pixel wide border around it. For the copyright image to be clear of the border, its top coordinate must be 511 plus the width of the top and bottom borders, for a total of 519 pixels. The left position is determined by the width of the main image (383 pixels) minus the width of the copyright image (120 pixels).
The choice of the div element as a container is driven by the block-level nature of the image in the layout. A div element is a convenient block-level container that lets you create an arbitrary HTML container wherever one is needed (see Recipe 13.4). Because an img element is not a container, it cannot be made a relative-positioned element that can contain an absolute-positioned element—thus the need for the div container.
This technique is also useful for overlapping elements. For example, instead of a copyright image, the page owner might prefer to overlay a transparent image that includes a subtle watermark-looking credit line. If the credit image is the same height and width as the underlying image, its absolute-positioned coordinates can be set to 0,0, corresponding to the top-left corner of the main image. However, if the watermark is a smaller image, it can be positioned anywhere on the image so that it is readable, yet doesn't detract from the view of the image.
13.2.4 See Also
The introduction to this chapter to understand the differences between absolute- and relative-positioned elements; Recipe 13.4 to help you know when to use a div or span element for positioning.