开发者

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

开发者 https://www.devze.com 2023-01-02 12:41 出处:网络
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?

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 开发者_StackOverflowquery 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();


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号