tags:

views:

3126

answers:

2

Best way to center a div on a page both vertically and horizontally?

I know that: margin-left: auto; margin-right: auto; Will center on the horizon but what is the best way to do it vertically too?

Thanks

+15  A: 

Dead Centre.

Unniloct
Of course, this is only useful if you have a fixed height box. Otherwise, you need to use some javascript to determine the height.
Ian
True. That's why I also voted up the other answer, because it's also good to have a dynamic solution.
Unniloct
+5  A: 

Here is a script i wrote a while back (it is written using the jQuery library):

var centerIt = function (el /* (jQuery element) Element to center */) {
    if (!el) {
     return;
    }
    var moveIt = function () {
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
    }; 
    $(window).resize(moveIt);
    moveIt();
};
Andreas Grech