私は通常、この「テクニック」を使用します。
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').width()/2,
'margin-top' : -$('.className').height()/2
});
});
アップデート:
ユーザーFredKが提案したように、とを使用.outerWidth()
し.outerHeight()
てより正確なセンタリングを行うために、ソリューションを更新しています。
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').outerWidth()/2,
'margin-top' : -$('.className').outerHeight()/2
});
});
jQueryのドキュメントからのいくつかの追加のメモ(.outerWidth()
、.outerHeight()
):
.outerWidth()を含むディメンション関連のAPIによって返される数は、場合によっては小数になることがあります。コードはそれが整数であると想定すべきではありません。また、ユーザーがページをズームすると、サイズが正しくない場合があります。ブラウザは、この状態を検出するためのAPIを公開していません。
.outerWidth()によって報告される値は、要素の親が非表示になっている場合に正確であるとは限りません。正確な値を取得するには、.outerWidth()を使用する前に、最初に親を表示する必要があります。
更新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}
});
});