我通常使用这个“技巧”:
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').width()/2,
'margin-top' : -$('.className').height()/2
});
});
更新:
我正在更新解决方案,如用户Fred K所建议的那样,使用.outerWidth()
和.outerHeight()
来实现更精确的居中。
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').outerWidth()/2,
'margin-top' : -$('.className').outerHeight()/2
});
});
以下是来自 jQuery 文档 (.outerWidth()
, .outerHeight()
) 的一些额外说明:
更新 2:
简单的更新,展示了如何在存在具有不同大小的相同 class
标签的多个元素中,在 css()
方法内使用 this
。
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : function() {return -$(this).outerWidth()/2},
'margin-top' : function() {return -$(this).outerHeight()/2}
});
});
outerWidth()
和outerHeight()
确保获取中心。 - Fred Kclass
标签不够具体,可以在css()
方法中传递一个函数作为参数,以避免使用each()
方法。我会添加一个快速更新。 - Dim13i