Some time we need to set a div at the center of the browser irrespective of different resolutions of output screen.
Height attribute set as 100% won’t work. If we set height in pixels then too it may not show properly at the center on screen with different resolutions. So, here is a solution I found in which we can use Javascript to accomplish our task.
Below is the javascript function which needs to be called in onload event of html page body.
function ShowDivInCenter() { try { divWidth = 100; divHeight = 100; divId = 'divLogin'; // id of the div that you want to show in center // Get the x and y coordinates of the center in output browser's window var centerX, centerY; if (self.innerHeight) { centerX = self.innerWidth; centerY = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { centerX = document.documentElement.clientWidth; centerY = document.documentElement.clientHeight; } else if (document.body) { centerX = document.body.clientWidth; centerY = document.body.clientHeight; } var offsetLeft = (centerX - divWidth) / 2; var offsetTop = (centerY - divHeight) / 2; // The initial width and height of the div can be set in the // style sheet with display:none; divid is passed as an argument to // the function var ojbDiv = document.getElementById(divId); ojbDiv.style.position = 'absolute'; ojbDiv.style.top = offsetTop + 'px'; ojbDiv.style.left = offsetLeft + 'px'; ojbDiv.style.display = "block"; } catch (e) {} }
Now call this function in the onload event of body like below:
– This trick also works to keep the div at the center, when you resize the browser, if you call the same function in the body at onresize event:
<body onload='ShowDivInCenter();' onresize='ShowDivInCenter();'> <body onload='ShowDivInCenter();' onresize='ShowDivInCenter();'>