Centering a div vertically & horizontally using jQuery

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

    I normally use this "technique":

    $(function() {
        $('.className').css({
            'position' : 'absolute',
            'left' : '50%',
            'top' : '50%',
            'margin-left' : -$('.className').width()/2,
            'margin-top' : -$('.className').height()/2
        });
    });
    

    UPDATE:

    I'm updating the solution, as suggested by the user Fred K, using .outerWidth() and .outerHeight() to have a more precise centering.

    $(function() {
        $('.className').css({
            'position' : 'absolute',
            'left' : '50%',
            'top' : '50%',
            'margin-left' : -$('.className').outerWidth()/2,
            'margin-top' : -$('.className').outerHeight()/2
        });
    });
    

    Some additional notes from jQuery' documentation (.outerWidth(), .outerHeight()):

    • The number returned by dimensions-related APIs, including .outerWidth(), may be fractional in some cases. Code should not assume it is an integer. Also, dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition.

    • The value reported by .outerWidth() is not guaranteed to be accurate when the element's parent is hidden. To get an accurate value, you should show the parent first, before using .outerWidth().


    UPDATE 2:

    A simple update to show how you could use this inside the css() method in case there are more elements with the same class tag with different sizes.

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

提交回复
热议问题