jQueryを使用してDIVを画面中央に配置する

Last Updated:2023年07月16日| | コメントを残す

jQueryを使用してDIVを画面中央(中央)に配置するには、次のjQueryのスクリプトを使用することができます。

jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
// Source: stackoverflow

次のコードで上位DIVの中央に配置されます。

$("element").center();

垂直(垂直)では中央揃えを必要としない場合はthis.css( "top"、...); 行を削除するだけです。

次のようなjQueryのスクリプトも可能です。

$.fn.center = function() {
this.css({
'position': 'fixed',
'left': '50%',
'top': '50%'
});
this.css({
'margin-left': -this.outerWidth() / 2 + 'px',
'margin-top': -this.outerHeight() / 2 + 'px'
});

return this;
}

jQueryの代わりに簡単に次のようなCSSコードを使用することもできます。

.center {
position: absolute; /* */
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 48%;
height: 59%;
}

CSSを使用する場合は、上記のコードより div内のdivを中央に配置する 記事で紹介された方法を試してみてください。 ほとんどのケースでうまく動作します。


コメントを残す

コメント