divを水平と垂直に中央に配置

4130 ワード

1.cssスタイル実装
    #demo {
        position: absolute;
        width: 200px;
        height: 200px;
        left: 50%;
        top: 50%;
        margin: -100px 0 0 -100px;
        background: #5BBF5A;
    }

要素の位置決めをペアに基づいて位置決めし、leftとtopを最近の位置決めされた祖先要素の50%に対して設定し、divの上外辺距離と左外辺距離を要素の幅と半分以上の負の値に設定します.この実装方式は,幅と高固定divにのみ有効である.
2.javascript実装
    #demo {
        position: absolute;
        width: 200px;
        height: 200px;
        background: #5BBF5A;
    }

    function makeElementCenter (element){
        //          
        var pageWidth = document.documentElement.clientWidth;
        var pageHeight = document.documentElement.clientHeight;

        //      
        var elementWidth = element.offsetWidth;
        var elementHeight = element.offsetHeight;

        element.style.left = (pageWidth - elementWidth) / 2 + 'px';
        element.style.top = (pageHeight - elementHeight) / 2 + 'px';
    }

この方式は幅と高さを固定しないdivにも有効である.
3.jquery実装
    #demo {
        position: absolute;
        width: 200px;
        height: 200px;
        background: #5BBF5A;
    }

    $(".demo").css({ 
        left: ($(window).width() - $(".demo").outerWidth()) / 2, 
        top: ($(window).height() - $(".demo").outerHeight()) / 2 
    });

原理はjavascriptの実現原理と同じです