将div垂直居中&amp ;;水平使用jQuery [英] Centering a div vertically & horizontally using jQuery

查看:113
本文介绍了将div垂直居中&amp ;;水平使用jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此脚本将div水平和垂直居中.

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

当页面加载时,div会垂直居中,直到我调整浏览器大小后才会居中.

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

我在做什么错了?

$(document).ready(function (){
    $(window).resize(function (){
        $('.className').css({
            position:'absolute',
            left: ($(window).width() - $('.className').outerWidth())/2,
            top: ($(window).height() - $('.className').outerHeight())/2
        });
    });
    $(window).resize();
});

推荐答案

我通常使用这种技术":

I normally use this "technique":

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


更新:

根据用户 Fred K 的建议,我正在更新解决方案. ,使用 .outerWidth()

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
    });
});

jQuery文档中的一些附加说明( .outerWidth()

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

  • 在某些情况下,尺寸相关的API返回的数字(包括.outerWidth())可能是小数.代码不应假定它是整数.另外,当用户缩放页面时,尺寸可能不正确;浏览器不会公开API来检测这种情况.

  • 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.

隐藏元素的父级时,不能保证.outerWidth()报告的值是准确的.要获得准确的值,应先显示父对象,然后再使用.outerWidth().

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().


更新2:

一个简单的更新,显示了如何在css()方法内部使用this,以防出现更多具有相同class标签的元素,且大小不同.

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}
    });
});

这篇关于将div垂直居中&amp ;;水平使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆