Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 609
Jimbo Avatar asked Jun 02 '10 10:06

Jimbo


1 Answers

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.

like image 83
T.J. Crowder Avatar answered Sep 17 '22 14:09

T.J. Crowder