Or would you have to center the element in some other manner? If so, how? Right now the only way I'm seeing is to set specific coordinates initially, but then of course it won't be centered in every instance. Thanks!

1 answer

1
point

I would center the element using jQuery, not via CSS. If you calculate the page size correctly and the element's size and then position it, it will be centered every time. This function is useful for getting the page width, height reliably across browsers:

  // getPageSize()
  // Returns array with page width, height and window width, height.
  // Core code from - quirksmode.com.
  // Edit for Firefox by pHaez.
  // Usage: Call getPageSize() and after that you can access arrayPageSize as follows:
  // arrayPageSize[1] = page width
  // arrayPageSize[2] = page height
  // arrayPageSize[3] = window width
  // arrayPageSize[4] =  window height   


  function getPageSize() {

    var xScroll, yScroll;

    if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
      xScroll = document.body.scrollWidth;
      yScroll = document.body.scrollHeight;
    }
    else if (window.innerHeight && window.scrollMaxY) {
      xScroll = window.innerWidth + window.scrollMaxX;
      yScroll = window.innerHeight + window.scrollMaxY;
    }
    // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari.
    else {
      xScroll = document.body.offsetWidth;
      yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

    if (self.innerHeight) { // All except Explorer.
      if (document.documentElement.clientWidth) {
        windowWidth = document.documentElement.clientWidth;
      }
      else {
        windowWidth = self.innerWidth;
      }
      windowHeight = self.innerHeight;
    }
    // Explorer 6 Strict Mode.
    else if (document.documentElement && document.documentElement.clientHeight) {
      windowWidth = document.documentElement.clientWidth;
      windowHeight = document.documentElement.clientHeight;
    }
    else if (document.body) { // Other Explorers.
      windowWidth = document.body.clientWidth;
      windowHeight = document.body.clientHeight;
    }


    // For small pages with total height less then height of the viewport.
    if (yScroll < windowHeight) {
      pageHeight = windowHeight;
    }
    else {
      pageHeight = yScroll;
    }


    // For small pages with total width less then width of the viewport.
    if (xScroll < windowWidth) {
      pageWidth = windowWidth;
    }
    else {
      pageWidth = xScroll;
    }

    arrayPageSize = [pageWidth, pageHeight, windowWidth, windowHeight];
    return arrayPageSize;
  }
Answered about 6 years ago by Moin Zaman