0

I am using this code to center myDiv to active screen. (taken from Using jQuery to center a DIV on the screen)


$("#myDiv").css("position","absolute");
$("#myDiv").css("top", Math.max(0, (($(window).height() - $("#myDiv").outerHeight()) / 2) + $(window).scrollTop()) + "px");
$("#myDiv").css("left", Math.max(0, (($(window).width() - $("#myDiv").outerWidth()) / 2) + $(window).scrollLeft()) + "px");

Code works perfectly if the page is loaded in browser window and correctly centered the myDiv to active screen (ignoring the length of page no matter I am having lots of scrolling down or above).

But when the page is loaded within iframe then the code is not working as per expectations and centers the DIV (vertically) according to complete length of content (not the active screen). So if I am at the top of screen and page is let say 3000px long then the code will show the myDiv down there at 1500px, where as if page is loaded in browser window then myDiv will be shown according to whatever is the current active screen/scroll position.

I want to center the div as per the current active screen/scroll. No matter page is loaded in browser window or the iframe. Any help?

Thanks in advance,

Community
  • 1
  • 1
Gulfam
  • 558
  • 6
  • 27

2 Answers2

0

Try this CSS-only solution:

#myDiv {
  position: fixed;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  transform: translate(-50%; -50%);
}

This code moves the top-left-corner of #myDiv to 50% of the viewports X- and Y-axis. Using translate with negative values, moves #myDiv 50% of its own width back and both X- and Y-axis.

CSS3 Transform are not supported by older browsers, keep that in mind.

Kilian Stinson
  • 2,376
  • 28
  • 33
  • this don't work either and centers the myDiv down according to the length of contents and not the active screen. – Gulfam Jan 09 '14 at 07:32
0

It was a cross domain issue, I had to pass coordinates in order to centralize Div in iFrame.

Gulfam
  • 558
  • 6
  • 27