简体   繁体   中英

Vertically center content with jQuery

I am trying to center my entire content with jQuery. I've tried multiple solutions that have been posted but to no availability. My major problem is that it needs to work with IE6 thru IE8.

Here is the link: http://christopherburton.net/ie

$(function() {
    var $inner = $('#container');

    $inner.css({ marginTop:  ($(window).height() / 2) - $inner.outerHeight() / 2 });
});

That would calculate and set the correct margin-top value once. If you want to update that when someone resizes the browser window, you need to call that code in a resize event on the window object aswell. Like

$(function() {
    var $inner = $('#container');
    $(window).on('resize', function() {
        $inner.css({ marginTop:  ($(window).height() / 2) - $inner.outerHeight() / 2 });
    });
});
$( "elem" ).css({
    position: "absolute",
    top: "50%",
    marginTop: "-" + $( "elem" ).height() / 2 + "px"
});

Should work.

You don't need jQuery for that ..

Use CSS

Use this for Container class

#container {
position: absolute;
width: 525px;
height: 220px;
margin: 0 auto;
left: 35%;
top: 30%;
}

添加这些样式后检查

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