Common Positioning Tasks
This chapter concludes with examples of two common positioning tasks: centering objects and flying objects. A third task, user-controlled dragging of objects, is kept on hold until Chapter 6, where we discuss the browser event models.
Centering an Object
The common way to center an element within a rectangle is to calculate the half-way point along each axis for both the element and its containing rectangle (positioning context). Then subtract the element value from the container value for each axis. The resulting values are the coordinates for the top and left edges of the element that center the element.
Document object properties and references differ so widely for these attributes in Navigator and Internet Explorer that it takes a bit of code to handle the centering task for both browsers in the same document. The calculations rely on browser-specific functions that might best be placed into a custom API and linked in from an external .js file. For purposes of demonstration, however, the library functions are embedded into the example document shown here.
The element being centered in the browser window is an outer
DIV element with a yellow background. Inside this
DIV element is a one-word P
element, which, itself, is positioned inside the context of the
DIV element. The goal is to center the outer
DIV element, bringing the contained paragraph
along for the ride. Example 4.6 shows the complete
page listing.
Example 4-6. A Page That Centers an Element ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access