Centering a div vertically & horizontally using jQuery

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

    based on @dimi's answer, works better with multiple elements

    $(".className").each(
        function () {
           $( this ).css("position","absolute");
           $( this ).css("left","50%");
           $( this ).css("margin-left", - $( this ).outerWidth()/2 );
           $( this ).css("top","50%");
           $( this ).css("margin-top", - $( this ).outerHeight()/2 );
           return this;
        }
    );
    

提交回复
热议问题