Jak wyśrodkować element html w oknie przeglądarki?

Jak mogę umieścić jakiś element html, powiedzmy div, na środku okna przeglądarki (Nie strona, nie Ekran)? Nie zależy od rozmiaru okna przeglądarki, rozdzielczości ekranu, układu paska narzędzi itp. Np. chcę, aby był on w środku okna przeglądarki .

Thanks

 52
Author: iliketocode, 2009-06-11

18 answers

Aby to zrobić, musisz znać rozmiar elementu, który centrujesz. Px, em, procent), ale musi mieć stały rozmiar.

Css będzie wyglądał następująco:

 // Replace X and Y with a number and u with a unit. do calculations
 // and remove parens
.centered_div {
   width: Xu;
   height: Yu;
   position: absolute;
   top: 50%;
   left: 50%;
   margin-left: -(X/2)u;
   margin-top: -(Y/2)u;
}

Edit : to miejsce w widoku. Możesz wyśrodkować tylko w oknie przeglądarki za pomocą JavaScript. Ale to może być wystarczająco dobre, ponieważ prawdopodobnie chcesz wyświetlić okno popup / modal?

 36
Author: PatrikAkerstrand,
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
2009-06-11 16:15:46

Jest to całkowicie możliwe tylko przy użyciu CSS - nie wymaga JavaScript: Oto przykład

Oto kod źródłowy tego przykładu:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>  
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">
<title>Dead Centre</title>  
<style type="text/css" media="screen"><!--
body 
    {
    color: white;
    background-color: #003;
    margin: 0px
    }

#horizon        
    {
    color: white;
    background-color: transparent;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 0px;
    width: 100%;
    height: 1px;
    overflow: visible;
    visibility: visible;
    display: block
    }

#content    
    {
    font-family: Verdana, Geneva, Arial, sans-serif;
    background-color: transparent;
    margin-left: -125px;
    position: absolute;
    top: -35px;
    left: 50%;
    width: 250px;
    height: 70px;
    visibility: visible
    }

.bodytext 
    {
    font-size: 14px
    }

.headline 
    {
    font-weight: bold;
    font-size: 24px
    }

#footer 
    {
    font-size: 11px;
    font-family: Verdana, Geneva, Arial, sans-serif;
    text-align: center;
    position: absolute;
    bottom: 0px;
    left: 0px;
    width: 100%;
    height: 20px;
    visibility: visible;
    display: block
    }

a:link, a:visited 
    {
    color: #06f;
    text-decoration: none
    }

a:hover 
    {
    color: red;
    text-decoration: none
    }

--></style>
</head>
<body>
<div id="horizon">
    <div id="content">
        <div class="bodytext">
        This text is<br>
        <span class="headline">DEAD CENTRE</span><br>
        and stays there!</div>
    </div>
</div>
<div id="footer">
    <a href="http://www.wpdfd.com/editorial/thebox/deadcentre4.html">view construction</a></div>
</body>
</html>
 11
Author: Cuga,
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
2009-06-11 16:24:41

Oto:

  • HTML + CSS only solution-no JavaScript needed
  • to nie wymaga, aby znać rozmiar zawartoÅ›ci z góry
  • zawartość stoi na Å›rodku okna zmiany rozmiaru

I przykład:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML centering</title>

        <style type="text/css">
        <!--
        html, body, #tbl_wrap { height: 100%; width: 100%; padding: 0; margin: 0; }
        #td_wrap { vertical-align: middle; text-align: center; }
        -->
        </style>
    </head>

    <body>
        <table id="tbl_wrap"><tbody><tr><td id="td_wrap">
        <!-- START: Anything between these wrapper comment lines will be centered -->


<div style="border: 1px solid black; display: inline-block;">
This content will be centered.
</div>

        <!-- END: Anything between these wrapper comment lines will be centered -->
        </td></tr></tbody></table>
    </body>
</html>

Spójrz na oryginalny adres URL, aby uzyskać pełne informacje: http://krustev.net/html_center_content.html

Możesz robić, co chcesz z tym kodem. Jedynym warunkiem jest to, że każda praca pochodna musi mieć odniesienie do autor oryginału.
 11
Author: Delian Krustev,
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-05-10 16:31:11

Zdziwiłem się, że nikt nie powiedział o pozycji = naprawione. Robi dokładnie to, o co prosiłem i działa we wszystkich "ludzkich" przeglądarkach i IE od 7.

 10
Author: Kamarey,
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
2009-06-13 15:19:59
div#wrapper {
    position: absolute;
    top:  50%;
    left: 50%;
    transform: translate(-50%,-50%);
}
 10
Author: Saman Sadeghpour,
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-06-24 14:34:17

Miałem wiele problemów z centrowaniem i wyrównaniem, dopóki nie znalazłem Flexbox jako zalecenia w przewodniku.

Kompletny przewodnik po Flexbox

Wrzucę tu fragment (który działa z Chrome ' Em) dla wygody:

<head>
    <style type="text/css">
        html
        {
            width: 100%;
            height: 100%;
        }

        body
        {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>

<body>
    This is text!
</body>

Aby uzyskać więcej informacji, zapoznaj się z artykułem.

 4
Author: yaganox,
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
2013-09-08 17:41:17

Jeśli nie znasz rozmiaru przeglądarki, możesz po prostu wyśrodkować w CSS następujący kod:

Kod HTML:

<div class="firstDiv">Some Text</div>  

Kod CSS:

 .firstDiv {
  width: 500px;

  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  background-color: #F1F1F1;
 }
To również pomaga w nieprzewidzianych zmianach w przyszłości.
 4
Author: Anand Mohanty,
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-04-14 14:46:35

Aby wyśrodkować wyrównanie div należy zastosować styl

div 
{
    margin: 0 auto;
}
 2
Author: gonzohunter,
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
2009-06-11 16:20:39
<div align="center">

Lub

<div style="margin: 0 auto;">
 1
Author: threadhack,
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
2009-06-11 16:16:03

To jest zaznaczone i działa we wszystkich przeglądarkach.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <style type="text/css">
            html, body { margin: 0; padding: 0; height: 100%; }

            #outer {height: 100%; overflow: hidden; position: relative; width: 100%;}
            #outer[id] {display: table; position: static;}

            #middle {position: absolute; top: 50%; width: 100%; text-align: center;}
            #middle[id] {display: table-cell; vertical-align: middle; position: static;}

            #inner {position: relative; top: -50%; text-align: left;}
            #inner {margin-left: auto; margin-right: auto;}
            #inner {width: 300px; } /* this width should be the width of the box you want centered */
        </style>
    </head>
    <body>

        <div id="outer">
            <div id="middle">
                <div id="inner">
                    centered
                </div>
            </div>
        </div>

    </body>
</html>
 1
Author: Michal M,
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
2009-06-11 16:38:27

Jest to świetne podejście responsywne do absolutne Centrowanie

Zgodność przeglądarki: Chrome, Firefox, Safari, Mobile Safari, IE8-10.

Zalety:

  • Cross-browser (w tym IE8-10)
  • Brak specjalnych znaczników, Minimalne Style
  • responsywne z procentami i min - / max -
  • użyj jednej klasy, aby wyÅ›rodkować dowolnÄ… zawartość
  • wyÅ›rodkowane niezależnie od wypeÅ‚nienia (bez rozmiaru pudeÅ‚ka!)
  • bloki można Å‚atwo be resized
  • Å›wietnie sprawdza siÄ™ na zdjÄ™ciach

Zastrzeżenia:

  • Wysokość musi być zadeklarowana (patrz zmienna Wysokość)
  • Aby zapobiec rozlewaniu siÄ™ zawartoÅ›ci, zaleca siÄ™ ustawienie overflow: auto (zobacz Overflow)
  • nie dziaÅ‚a na Windows Phone
 1
Author: ikertxu,
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
2013-10-06 13:39:04

Myślę, że nie możesz tego zrobić. Możesz znajdować się w środku dokumentu, jednak nie znasz układu paska narzędzi ani rozmiaru elementów sterujących przeglądarki. W ten sposób możesz wyśrodkować dokument, ale nie w środku okna przeglądarki.

 0
Author: Pim Jager,
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
2009-06-11 16:14:49

Jeśli rozumiem, że masz rację, chcesz wyśrodkować element w pionie i poziomie na podstawie okna, a nie dokumentu. Może to być trochę bolesne, ale możesz użyć javascript, aby wykryć rozmiar okna, pozycję przewijania, Rozmiar elementu itp. a następnie umieść element na środku okna (Nie dokument, ale okno do przeglądania).

Jeśli chcesz, aby ten element pozostał w module okna podczas przewijania, musisz uchwycić Zdarzenie przewijania i dostosować pozycji.

Kod do tego celu różni się w zależności od przeglądarki.

 0
Author: James Conigliaro,
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
2009-06-11 16:19:46

Możesz napisać skrypt JavaScript, aby znaleźć wysokość i szerokość okna i zrobić go do połowy, aby znaleźć punkt środkowy.

Dodaj rzeczy wewnątrz znacznika i ustaw div na górze i na lewo od javascript do współrzędnych środkowych, które znalazłeś za pomocą Javascript.

Daj znać, jeśli będziesz potrzebował kodu.

 0
Author: Bhaskar,
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
2009-06-11 16:25:40

Mam nadzieję, że to pomoże. Sztuczka polega na użyciu bezwzględnego pozycjonowania i skonfigurowaniu górnej i lewej kolumny. Oczywiście "martwe centrum" będzie zależeć od rozmiaru osadzanego obiektu/div, więc będziesz musiał wykonać pewną pracę. W oknie logowania użyłem następującego - ma również pewne bezpieczeństwo z maksymalną szerokością i maksymalną wysokością, które mogą być rzeczywiście przydatne w twoim przykładzie. Skonfiguruj poniższe wartości zgodnie z wymaganiami.

div#wrapper {
    border: 0;
    width: 65%;
    text-align: left;
    position: absolute;
    top:  20%;
    left: 18%;
    height: 50%;
    min-width: 600px;
    max-width: 800px;
}
 0
Author: Ryan Oberoi,
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
2009-06-11 16:37:20

RozwiÄ…zanie robocze.

<html>
          <head>
            <style type="text/css">
                html
                {
                    width: 100%;
                    height: 100%;
                }

                body
                {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
            </style>
        </head>

        <body>
            Center aligned text.(horizontal and vertical side)
        </body>
</html>
 0
Author: Vinayak,
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-22 12:13:02

U mnie działa :).

div.parent {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
 0
Author: Kiry Meas,
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
2018-05-31 14:59:52

Możesz wyśrodkować dowolny obiekt w viewport, oto przykład używając jquery

$(document).ready(function()
{


posicionar("#midiv");
$(window).on("resize", function() {
    posicionar("#midiv");   
});

function posicionar(elemento){
    var altoDocumento = $(window).height();//alto
    var anchoDocumento = $(window).width();
    //console.log(altoDocumento);
    //console.log(anchoDocumento);
    var centroXDocumento = anchoDocumento / 2;
    var centroYDocumento = altoDocumento / 2;
    //console.log(centroXDocumemnto,centroYDocumento);
    var altoElemento = $(elemento).outerHeight(true);//ancho real del elemento
    var anchoElemento = $(elemento).outerWidth(true);//alto 

    var centroXElemento = anchoElemento / 2;// centro x del elemento
    var centroYElemento = altoElemento / 2; // centro y del elemento

    var posicionXElemento = centroXDocumento - centroXElemento;
    var posicionYElemento = centroYDocumento - centroYElemento;

    $(elemento).css("position","absolute");
    $(elemento).css("top", posicionYElemento);
    $(elemento).css("left", posicionXElemento);
}
});

Html

<div id="midiv"></div>

Uwaga: musisz wykonać funkcję onDomReady i gdy okno zmieni rozmiar.

Oto de jsfiddle http://jsfiddle.net/geomorillo/v82x6/

 -1
Author: Geomorillo,
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
2013-12-27 22:03:25