Centering a div vertically & horizontally using jQuery

后端 未结 9 1316
轮回少年
轮回少年 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:08

    Wrap the handler code in a function so you can call that function both on page load as well as handler for $(window).resize()

    /* use as handler for resize*/
    $(window).resize(adjustLayout);
    /* call function in ready handler*/
    $(document).ready(function(){
        adjustLayout();
        /* your other page load code here*/
    })
    
    function adjustLayout(){
        $('.className').css({
            position:'absolute',
            left: ($(window).width() - $('.className').outerWidth())/2,
            top: ($(window).height() - $('.className').outerHeight())/2
        });
    
    }
    

提交回复
热议问题