Centrowanie div w pionie i poziomie przy użyciu jQuery

Używam tego skryptu, aby wyśrodkować mój div poziomo i pionowo.

Gdy strona ładuje div zostanie wyśrodkowany w pionie, nie w poziomie, dopóki nie zmienię rozmiaru przeglądarki.

Co robię źle?
$(document).ready(function (){
    $(window).resize(function (){
        $('.className').css({
            position:'absolute',
            left: ($(window).width() - $('.className').outerWidth())/2,
            top: ($(window).height() - $('.className').outerHeight())/2
        });
    });
    $(window).resize();
});
Author: Pranav 웃, 2012-12-16

9 answers

Normalnie używam tej "techniki":

$(function() {
    $('.className').css({
        'position' : 'absolute',
        'left' : '50%',
        'top' : '50%',
        'margin-left' : -$('.className').width()/2,
        'margin-top' : -$('.className').height()/2
    });
});

UPDATE:

Aktualizuję rozwiązanie, zgodnie z sugestią użytkownika Fred K, za pomocą .outerWidth() oraz .outerHeight() aby mieć bardziej precyzyjne centrowanie.

$(function() {
    $('.className').css({
        'position' : 'absolute',
        'left' : '50%',
        'top' : '50%',
        'margin-left' : -$('.className').outerWidth()/2,
        'margin-top' : -$('.className').outerHeight()/2
    });
});

Kilka dodatkowych uwag z dokumentacji jQuery(.outerWidth(), .outerHeight()):

  • Liczba zwracana przez interfejsy API związane z wymiarami, w tym .outerWidth (), może być ułamkowe w niektórych przypadkach. Kod nie powinien zakładać, że jest liczbą całkowitą. Ponadto wymiary mogą być nieprawidłowe, gdy strona jest powiększana przez użytkownika; przeglądarki nie narażają API na wykrycie tego warunku.

  • Wartość podana przez .outerWidth () nie gwarantuje dokładności, gdy element nadrzędny jest ukryty. Aby uzyskać dokładną wartość, powinieneś najpierw pokazać rodzica ,przed użyciem.outerWidth ().


Aktualizacja 2:

A prosta aktualizacja pokazująca, jak można użyć this wewnątrz metody css() W przypadku, gdy jest więcej elementów z tym samym znacznikiem class o różnych rozmiarach.

$(function() {
    $('.className').css({
        'position' : 'absolute',
        'left' : '50%',
        'top' : '50%',
        'margin-left' : function() {return -$(this).outerWidth()/2},
        'margin-top' : function() {return -$(this).outerHeight()/2}
    });
});
 59
Author: Dim13i,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:37

Użyj tego, aby wyśrodkować:

$.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();
 20
Author: Jai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-16 17:27:41

Zawiń kod obsługi w funkcję, dzięki czemu możesz wywołać tę funkcję zarówno podczas ładowania strony, jak i obsługi dla $(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
    });

}
 9
Author: charlietfl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-16 17:31:22

Powiązane z fragmentem kodu, musisz najpierw ustawić pozycję:

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

Może mógłbyś ustawić atrybut position za pomocą statycznego stylu CSS.

 3
Author: Matthias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-16 17:45:52

Na podstawie odpowiedzi @ dimi, działa lepiej z wieloma elementami

$(".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;
    }
);
 1
Author: mabi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-10 10:26:01

Używam tego JQuery.center wtyczka do wyśrodkowania elementów DOM. Kod będzie taki:

$("#child").center()

Poprzedni kod będzie wyśrodkowany względem bezpośredniego rodzica, jeśli chcesz wyśrodkować względem innego rodzica, będzie to:

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

Istnieją niestandardowe opcje, jeśli potrzebujesz innej formy centralizacji.

 0
Author: Mustafah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-11 22:34:33

Ostatnio próbowałem umieścić pudełko na środku okna przeglądarki. Stworzyłem poniższy kod. Skrypt jQuery jest dość długi, ponieważ wziąłem pod uwagę wszystkie paddingi i marginesy znaczników html i body, jeśli ktoś je ustawił. Jeśli ktoś nie dba o Tło, to tylko winwidth, winheight, toppx, leftpx i "#container" muszą być ustawione. Reszta może zostać usunięta.

<!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>





Edytuj: Znalazłem dużo lepsze rozwiązanie dla tego na CSS Tricks Strona i używa tylko CSS :). Kod jest poniżej:

<!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>
 0
Author: Celdor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-24 12:16:32

Mój div z class center musi być wyśrodkowany poziomo w środku i jego pozycja jest stała. Używam tego małego kodu, aby to się stało:

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

Możesz użyć tej samej taktyki do wyrównania poziomego. Spójrz, że obsługuje jednocześnie zdarzenia load I resize, więc ten div jest zawsze pośrodku.

 0
Author: Lukas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-17 21:10:56

Możesz użyć tej wtyczki, która jest bardzo prosta w użyciu https://github.com/tenbullstech/jquery-make-me-center

$("div.box").makemecenter();
 0
Author: Aman Bansal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-25 16:46:36