To centre an element, that has an absolute position, to a page, we must first discover some properties of the current window:
- · Window size (getWindowSize())
- · Window scroll position (getScrollXY())
If our element is for example:
<div id="sample" style="width:100px;height:100px;border:1px solid #000;position:absolute:z-index:10">sample</div>
...whose element is represented by the variable obj (for this example):
obj = document.getElementById("sample");
We want to set the x and y positions of this element.
Firstly recover the properties:
Now define the top y position of the element:
elementTop = (obj.clientHeight> winsize[1])? scrolls[1]:(( winsize[1]-obj.clientHeight)/2)+ scrolls[1];
This says that is the element is taller than the page, then we shall put the top at the scroll position to ensure the top of the element is visible, otherwise we set the top to the window height – the element height divided by 2 plus the scroll position.
To stop the element abutting the top of the page, we can offset it slightly:
if (elementTop<10) elementTop = 10;
Next define the left edge position of the element:
elementLeft = (document.body.offsetWidth-obj.clientWidth)/2;
If the element is wider than the page, this value will be negative so:
if (elementLeft<0) elementLeft = 0;
Now set the element position:
obj.style.left = elementLeft+"px";
obj.style.top = elementTop+"px";
Place this inside a function for easy use:
function centerObject(obj) {
scrolls=getScrollXY();
winsize = getWindowHeight();
elementTop = (obj.clientHeight>winsize[1])?scrolls[1]:((winsize[1-obj.clientHeight)/2)+ scrolls[1];
if (elementTop <10) elementTop =10;
elementLeft =((document.body.offsetWidth-obj.clientWidth)/2);
if (elementLeft<0) elementLeft=0;
obj.style.left= elementLeft +"px";
obj.style.top= elementTop +"px";
}
So now we can centre an object to the page by calling:
centerObject(document.getElementBy(“sample”);
or if to centre the object once it has loaded (like an image) we can set the onload parameter:
onclick="centerObject(this)"