views:

477

answers:

3

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();
A: 

Try this little article about Horizontal and Vertical centering. It is a little old and has a few hacks but you should be able to work out some test code from it.

Ólafur Waage
+1  A: 

This is easy to do with CSS if you have a fixed-size div:

.keepcentered {
    position:    absolute;
    left:        50%;        /* Start with top left in the center */
    top:         50%;
    width:       200px;      /* The fixed width... */
    height:      100px;      /* ...and height */
    margin-left: -100px;     /* Shift over half the width */
    margin-top:  -50px;      /* Shift up half the height */
    border: 1px solid black; /* Just for demo */
}

The problem, of course, is that fixed-size elements aren't ideal.

T.J. Crowder
Superstar, thanks! I have used it in the code posted below (posting code as a comment doesnt work well at all)
Jimbo
lol, +1up for funny comment
Neurofluxation
A: 

The simplest way would be with the following CSS code:

#floating-div {
width: 50%;
border: 1px solid gray;
margin: 0 auto;

}

The key line of CSS code above is the "margin: 0 auto;" which tells the browser to automatically set the left/right margins to keep the div centered on the page, even when you resize the browser window.

Bug Magnet
Doesn't keep it centred vertically though.
Blair McMillan
set the width and height, then try margin: auto auto;
MarkRobinson