How to center a div on screen
I will not explain here step by step how to do a function which will center a <div> on screen. Will use jQuery, just because I love it. If you are expecting to find the full code and just copy/paste it to your window, you will not find it. Still, everything is here, by snippets.
As a first, we need to ensure the content inside the div is fully loaded (e. g. images), or else we won’t determine the exact width and height of it. Unless the div is not getting changed after the page was loaded, it is enough to use the $(document).ready() function:
$(document).ready(function() {
// here is our code
});
Detecting the screen size
Here is where you can do the first mistake. Using $(window).height() may not be enough. For some browsers (such as Opera), you will not get the correct size and we need to use window.innerHeight instead. In this case, our code looks like this:
var winHeight = window.innerHeight ? window.innerHeight : $(window).height();
var winWidth = window.innerWidth ? window.innerWidth : $(window).width();
Getting the div size
This is easy, we simply use the height() and width() functions.
Centering the div
Will do it by simple math. Here you can do the 2nd mistake: do not allow negative values as result; part of the window will then get hidden and that content will not be visible and you won’t be even able to scroll to it!
var myTop=parseInt((winHeight-$('#myDiv').height())/2);
var myLeft=parseInt((winWidth-$('#myDiv').width())/2);
if(myTop < 0) myTop=0; if(myLeft < 0) myLeft = 0;
$('#myDiv').css({ "left" : myLeft + "px", "top" : myTop + "px"});
Now, our div is centered on the screen. Do not forget to style the div with a fixed position (position: fixed; on CSS part of your page/site). In many of the examples you will find, it is not fixed and this is the reason why the div will scroll once with the window. If you want it to remain centered, this is the way. Also, put a background color, maybe some borders. Without a background color, you will see both texts, the one form the newly centered div and the one the page already has. Also, the z-index property is important, you need the div to be over everything else on page. A style example follows:
#myDiv {
background-color: #FFFFFF;
border: 1px solid #AAAAAA;
display: none;
position: fixed;
top: 10px;
z-index: 100;
}
Of course, if you are using this to have kind of popup windows, you will need to have show/hide functions and maybe even an overlay layer or functions to detect the complete load of the div due to user interaction, but I’ll cover this topic on another tutorial.