How to keep a floating div centered on window resize (jQuery/CSS)

Posted by Jimbo on Stack Overflow See other posts from Stack Overflow or by Jimbo
Published on 2010-06-02T10:11:31Z Indexed on 2010/06/02 10:43 UTC
Read the original article Hit count: 156

Filed under:
|
|
|

Is there a way (without binding to the window.resize event) to force a floating DIV to re-center itself when the browser window is resized?

To help explain, I imagine the pseudocode would look something like:

div.left = 50% - (div.width / 2)
div.top = 50% - (div.height / 2)

UPDATE

My query having been answered below, I wanted to post the final outcome of my quest - a jQuery extension method allowing you to center any block element - hope it helps someone else too.

jQuery.fn.center = function() {
    var container = $(window);
    var top = -this.height() / 2;
    var left = -this.width() / 2;
    return this.css('position', 'absolute').css({ 'margin-left': left + 'px', 'margin-top': top + 'px', 'left': '50%', 'top': '50%' });
}

Usage:

$('#mydiv').center();

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery