📜 ⬆️ ⬇️

Center alignment of the visible part of the container

VisibleCentering It is necessary to place the element in the middle of the visible part of its container. If part of the container is hidden behind the scroll area, then the element should be placed in the center of the visible area. If the container is not visible at all, then the element is not visible with it. And if the container occupies the entire screen - the element should be in the middle of the screen.

Approximately as on the scheme on the right.

About the size of the element and its container is not known.
')
Here is an example of the page as I did it. On the page are three large divs, on average an element aligned to the center is placed. Checked in IE 6 & 7 (not my whim - the problem is this).

It is interesting to know how to make it easier and safer? And in Opera 9.5, for example, does not work. And I would like more universality of the code.

Relative (relative) positioning will place the element in the center of the container. Moreover, if the middle of the container is beyond the visible limits, then the element will not be visible (as in the figure). Fixed and static positioning methods are not suitable at all.

I used the absolute mode. And through prescribed properties left and top in the form of css expression:
.divVisibleCenter
{
position: absolute;
top: expression (GetVisibleCenterY (this));
left: expression (GetVisibleCenterX (this));
}


Calculations of the x and y coordinates of elements are made into separate JavaScript functions GetVisibleCenterX and GetVisibleCenterY, respectively:
function GetVisibleCenterX (item)
{
var c = item.parentNode;
var s = c.getBoundingClientRect ();
var right = c.document.documentElement.offsetWidth - ((s.right <c.document.documentElement.offsetWidth)? c.document.documentElement.offsetWidth-s.right: 0);
var left = c.offsetLeft + ((c.offsetLeft + s.left> c.offsetLeft + right)? 0: -s.left);
var offs = ((c.offsetLeft> left)? (c.offsetLeft - left): 0);
var width = right - offs;

return left + offs + (width / 2) - item.clientWidth / 2;
}
function GetVisibleCenterY (item)
{
var c = item.parentNode;
var s = c.getBoundingClientRect ();
var bottom = c.document.documentElement.offsetHeight - ((s.bottom <c.document.documentElement.offsetHeight)? c.document.documentElement.offsetHeight-s.bottom: 0);
var top = c.offsetTop + (((c.offsetTop + s.top> c.offsetTop + bottom)? 0: -s.top);
var offs = ((c.offsetTop> top)? (c.offsetTop - top): 0);
var height = bottom - offs;
return top + offs + (height / 2) - item.clientHeight / 2;
}

Source: https://habr.com/ru/post/27145/


All Articles