36

このスクリプトを使用して、divを水平方向と垂直方向の中央に配置しています。

ページが読み込まれると、ブラウザのサイズを変更するまで、divは水平方向ではなく垂直方向の中央に配置されます。

私は何が間違っているのですか?

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

9 に答える 9

63

私は通常、この「テクニック」を使用します。

$(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}
    });
});
于 2012-12-16T17:21:13.447 に答える
20

これを使用して中央に配置します。

$.fn.center = function () {
   this.css("position","absolute");
   this.css("top", ( $(window).height() - this.height() ) / 2  + "px");
   this.css("left", ( $(window).width() - this.width() ) / 2 + "px");
   return this;
}

$('yourElem').center();
于 2012-12-16T17:27:41.107 に答える
10

ハンドラーコードを関数でラップして、ページの読み込み時とハンドラーの両方でその関数を呼び出すことができるようにします。$(window).resize()

/* use as handler for resize*/
$(window).resize(adjustLayout);
/* call function in ready handler*/
$(document).ready(function(){
    adjustLayout();
    /* your other page load code here*/
})

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

}
于 2012-12-16T17:31:22.750 に答える
3

コードスニペットに関連して、最初に位置を設定する必要があります。

$(window).resize(function (){
    var $el = $('.className');
    $el.css('position', 'absolute').css({
        left: ($(window).width() - $el.width()) / 2,
        top: ($(window).height() - $el.height()) / 2
    });
});

静的CSSスタイルを介してposition属性を設定できるかもしれません。

于 2012-12-16T17:40:16.203 に答える
1

@dimiの回答に基づいて、複数の要素でより適切に機能します

$(".className").each(
    function () {
       $( this ).css("position","absolute");
       $( this ).css("left","50%");
       $( this ).css("margin-left", - $( this ).outerWidth()/2 );
       $( this ).css("top","50%");
       $( this ).css("margin-top", - $( this ).outerHeight()/2 );
       return this;
    }
);
于 2016-02-10T10:26:01.153 に答える
0

このJQuery.centerプラグインを使用して、DOM要素を中央に配置します。コードは次のようになります。

$("#child").center()

前のコードは直接の親を基準にして中央に配置されます。別の親を基準にして中央に配置する必要がある場合は、次のようになります。

$("#child").center($("#parent"))

他の形式の集中化が必要な場合は、カスタマイズされたオプションがあります。

于 2014-01-11T22:34:33.920 に答える
0

最近、ブラウザウィンドウの中央にボックスを配置しようとしています。以下のコードを作成しました。誰かが設定した場合、htmlとbodyタグのすべてのパディングとマージンを考慮したため、jQueryスクリプトは非常に長くなります。背景を気にしない場合は、winwidth、winheight、toppx、leftpx、および「#container」のみを設定する必要があります。残りは削除される場合があります。

<!DOCTYPE html>
<html>
<head>
    <title>Test of centre of container</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <style>
        html {
            background-color: #444;
            margin: 30px;
        }
        #wrapper {
            background-color: #777;
            width: 75%;
            margin: 0 auto;
            padding: 0;
        }
        #container {
            background-color: #ddd;
            border-radius: 10px;
            box-shadow: 0 0 2px #222;
            width: 200px;
            height: 100px;
            position: absolute;
            vertical-align: middle;
        }
        #extext {
            text-align: center;
            padding: 0;
        }
    </style>
</head>
<body>
    <script>
        function setDimensions() {
            var winwidth = $(window).width();
            var winheight = $(window).height();
            var htmlmv = parseInt($("html").css("margin-top")) + parseInt($("html").css("margin-bottom"));
            var htmlpv = parseInt($("html").css("padding-top")) + parseInt($("html").css("padding-bottom"));
            var htmlmh = parseInt($("html").css("margin-left")) + parseInt($("html").css("margin-right"));
            var htmlph = parseInt($("html").css("padding-left")) + parseInt($("html").css("padding-right"));
            var bodymv = parseInt($("body").css("margin-top")) + parseInt($("body").css("margin-bottom"));
            var bodypv = parseInt($("body").css("padding-top")) + parseInt($("body").css("padding-bottom"));
            var bodymh = parseInt($("body").css("margin-left")) + parseInt($("body").css("margin-right"));
            var bodyph = parseInt($("body").css("padding-left")) + parseInt($("body").css("padding-right"));
            var vspace = htmlmv + htmlpv + bodymv + bodypv;
            var hspace = htmlmh + htmlph + bodymh + bodyph;
            var wrapheight = winheight - vspace;
            var wrapwidth = winwidth - hspace;
            $("#wrapper").height(wrapheight);
            // $("#wrapper").width(wrapwidth);

            var toppx = (winheight - parseInt($("#container").css("height"))) / 2;
            var leftpx = (winwidth - parseInt($("#container").css("width"))) / 2;
            $("#container").css("top", toppx.toString() + "px");
            $("#container").css("left", leftpx.toString() + "px");
        }

        $(document).ready(function () {
            setDimensions();
        });
        $(window).resize(function () {
            setDimensions();
        });
    </script>
    <div id="wrapper">
        <div id="container">
            <p id="extext">Example text</p>
        </div>
    </div>
</body>
</html>





編集:CSS TricksのWebサイトでこれに対するはるかに優れた解決策を見つけましたが、CSSのみを使用しています:)。以下のコード:

<!DOCTYPE html>
<html>
<head>
    <title>
        Test centring!
    </title>
    <style>
        body div {
            background-color: red;
            box-shadow: 0 0 15px #222;
            border-radius: 10px;
            padding: 10px;
            margin: -150px auto auto -200px;
            width: 380px;
            height: 280px;
            position: absolute;
            top: 50%;
            left: 50%;
            text-align: center;
            line-height: 140px;
        }
        body div h2 {
            color: yellow;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <div>
        <h2>
            Example text<br />
            Example Text
        </h2>
    </div>
</body>
</html>
于 2014-08-22T01:19:20.290 に答える
0

クラスセンターのあるdivは、中央の水平方向の中央に配置する必要があり、その位置は固定されています。私はそれを実現するためにこの小さなコードを使用します:

$(window).on('resize load', function () {
    $('.center').each(function () {
        $(this).css({
            'margin-left': ($('body').width() - $(this).width()) / 2
        });
    });
});

水平方向の配置にも同じ戦術を使用できます。ロードイベントとサイズ変更イベントで同時に処理されることを確認してください。したがって、このdivは常に中央にあります。

于 2014-10-16T20:20:14.777 に答える
0

そのプラグインを使用できます。https://github.com/tenbullstech/jquery-make-me-centerを使用するのは非常に簡単です 。

$("div.box").makemecenter();
于 2015-05-25T16:46:36.740 に答える