简体   繁体   中英

Vertical centered div with jQuery

I am trying to center my div vertically in another div with 100% dimensions. My code is working but it gives some weird bug.

This is my code:

var window_height = $(window).height();
    var content_height = $('#home-content').height();
    var v_center_value = window_height / 2 - content_height / 2;
    $('#home-content').css({top: v_center_value});

I am also testing it on screefly to see how it acts on different resolutions. Overall, sometimes it works nice, sometimes it sends bigger value to my #home-content element and it falls below the center of the page.

It simply works whenever it wants.

Here is the web site I am testing - http://quirktools.com/screenfly/#u=http%3A//mkaramitev.free.bg&w=1366&h=768&a=1

And here is the original url - http://mkaramitev.free.bg

I might be wrong, but the problem you are experiencing might be because the tool you're using does not appear to do a full refresh when simulating dimension changes.

Your page is not responsive to window resizing between page loads. So, if a user loads your page and then resizes her browser, it will not recenter the design. That might be how you intend it. If not, you will need to bind an event handler to events the browser throws on resize in order to recenter the element.

jQuery has a resize method to bind to the resize event. Something like the following might work if you abstract your code out into another function.

$( window ).resize(function() {
    reposContent(); // this would be a call to your function
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM