• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

13. Positioning HTML Elements > 13.6. Centering an Element on Top of Another El...

Centering an Element on Top of Another Element

NN 6, IE 5

Problem

You want to position an element so that it is vertically and horizontally centered in front of an element in the main document flow.

Solution

The following centerOnElement( ) function takes two arguments: the ID of the main document element and ID of the positioned element to be placed there. The function is compatible with browsers that support W3C DOM element reference syntax:

function centerOnElement(baseElemID, posElemID) {
    baseElem = document.getElementById(baseElemID);
    posElem = document.getElementById(posElemID);
    
    var offsetTrail = baseElem;
    var offsetLeft = 0;
    var offsetTop = 0;
    // account for IE 6 CSS compatibility mode
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
   
    posElem.style.left = offsetLeft + parseInt(baseElem.offsetWidth/2) - 
       ....

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint