Centering a div vertically & horizontally using jQuery

后端 未结 9 1305
轮回少年
轮回少年 2020-12-02 08:44

I am using this script to center my div horizontally and vertically.

When the page loads the div gets centered vertically, not horizontally until I resize the brows

9条回答
  •  一整个雨季
    2020-12-02 09:00

    Related to your code snippet, you need to set the position first:

    $(window).resize(function (){
        var $el = $('.className');
        $el.css('position', 'absolute').css({
            left: ($(window).width() - $el.width()) / 2,
            top: ($(window).height() - $el.height()) / 2
        });
    });
    

    Maybe you could set the position attribute via a static CSS style.

提交回复
热议问题