我通常使用这种“技术”:
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').width()/2,
'margin-top' : -$('.className').height()/2
});
});
UPDATE:
我正在根据用户的建议更新解决方案Fred K https://stackoverflow.com/users/1252920/fred-k, using .outerWidth() http://api.jquery.com/outerwidth/ and .outerHeight() http://api.jquery.com/outerheight/以获得更精确的居中。
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').outerWidth()/2,
'margin-top' : -$('.className').outerHeight()/2
});
});
jQuery 文档中的一些附加注释(.outerWidth() http://api.jquery.com/outerwidth/, .outerHeight() http://api.jquery.com/outerheight/):
更新2:
一个简单的更新来展示如何使用this
在 - 的里面css()
方法,以防有更多具有相同的元素class
具有不同尺寸的标签。
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : function() {return -$(this).outerWidth()/2},
'margin-top' : function() {return -$(this).outerHeight()/2}
});
});