Jak wyśrodkować absolutnie pozycjonowany element w div?

Muszę umieścić div (z position:absolute;) element w środku mojego okna. Ale mam problemy z robieniem tego, ponieważ szerokość jest nieznana .

Próbowałem tego. Ale trzeba go dostosować, ponieważ szerokość reaguje.
.center {
  left: 50%;
  bottom:5px;
}
Jakieś pomysły?
Author: Sebastian Zartner, 2009-11-22

26 answers

<body>
  <div style="position: absolute; left: 50%;">
    <div style="position: relative; left: -50%; border: dotted red 1px;">
      I am some centered shrink-to-fit content! <br />
      tum te tum
    </div>
  </div>
</body>
 1199
Author: bobince,
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-09-09 09:41:38

To działa dla mnie:

#content {
  position: absolute; 
  left: 0; 
  right: 0; 
  margin-left: auto; 
  margin-right: auto; 
  width: 100px; /* Need a specific value to work */
}
<body>
  <div>
    <div id="content">
      I'm the content
    </div>
  </div>
</body>
 1660
Author: Matthias Weiler,
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-02-09 11:56:26

Rozwiązanie Responsywne

Oto dobre rozwiązanie dla responsywnego projektu lub nieznanych wymiarów ogólnie , Jeśli nie musisz obsługiwać IE8 i niższych.

.centered-axis-x {
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
}

.outer {
    position: relative; /* or absolute */
    
    /* unnecessary styling properties */
    margin: 5%;
    width: 80%;
    height: 500px;
    border: 1px solid red;
}

.inner {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    
    /* unnecessary styling properties */
    max-width: 50%;
    text-align: center;
    border: 1px solid blue;
}
<div class="outer">
    <div class="inner">I'm always centered<br/>doesn't matter how much text, height or width i have.<br/>The dimensions or my parent are irrelevant as well</div>
</div>

Oto Skrzypek JS

Wskazówka jest taka, że left: 50% jest względna do rodzica, podczas gdy translate transformacja jest względna do elementów szerokość/wysokość.

W ten sposób masz idealnie wyśrodkowany element, z elastyczną szerokością na obu dziecko i rodzic. Bonus: to działa, nawet jeśli dziecko jest większe niż rodzic.

Możesz również wyśrodkować go pionowo za pomocą tego (i znowu, szerokość i wysokość rodzica i dziecka mogą być całkowicie elastyczne (i / lub nieznane)): {]}
.centered-axis-xy {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

Pamiętaj, że możesz potrzebować transform przedrostka sprzedawcy. Na przykład -webkit-transform: translate(-50%,-50%);

 579
Author: ProblemsOfSumit,
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-07-14 17:52:51

Naprawdę fajny post.. Chciałem tylko dodać jeśli ktoś chce to zrobić z pojedynczym znacznikiem div to tutaj wyjście:

Biorąc width jako 900px.

#styleName {
    position: absolute;
    left: 50%;
    width: 900px;
    margin-left: -450px;
}

W tym przypadku należy znać width wcześniej.

 46
Author: pratikabu,
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-08-31 09:56:17

Absolute Centre

HTML:

<div class="parent">
  <div class="child">
    <!-- content -->
  </div>
</div>

CSS :

.parent {
  position: relative;
}

.child {
  position: absolute;

  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  margin: auto;
}

Demo: http://jsbin.com/rexuk/2/

Testowane w Google Chrome, Firefox i IE8

Mam nadzieję, że to pomoże:)

 31
Author: Ijas Ameenudeen,
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-03-24 09:38:50

Praca w pionie i poziomie

  #myContent{
        position: absolute;
        left: 0;
        right: 0;
        top:0;
        bottom:0;
        margin: auto;
   }

I jeśli chcesz, aby element był środkiem rodzica, ustaw pozycję rodzica relatywną

 #parentElement{
      position:relative
  }

Edit:

  • Dla pionowego wyrównania do środka Ustaw wysokość do elementu. dzięki @Raul

  • Jeśli chcesz, aby element był środkiem rodzica, ustaw pozycję rodzica na relatywną

 29
Author: Mohsen Abdollahi,
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-01-25 12:43:33

Szukając rozwiązania otrzymałem odpowiedzi powyżej i mogłem uczynić treść wyśrodkowaną z Matthias Weiler odpowiada, ale używając text-align.

#content{
  position:absolute;
  left:0;
  right:0;
  text-align: center;
}

Pracował z chrome i Firefox.

 18
Author: cavila,
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-05-29 01:36:45

Rozumiem, że to pytanie ma już kilka odpowiedzi, ale nigdy nie znalazłem rozwiązania, które sprawdziłoby się w prawie wszystkich klasach, które również ma sens i jest eleganckie, więc oto moje zdanie po kilku poprawkach: {]}

.container {
    position: relative;
}

.container .cat-link {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate3d(-50%,-50%,0);
    z-index: 100;
    text-transform: uppercase; /* Forces CSS to treat this as text, not a texture, so no more blurry bugs */
    background-color: white;
}

.color-block {
  height: 250px;
  width: 100%;
  background-color: green;
}
<div class="container">
  <a class="cat-link" href="">Category</a>
  <div class="color-block"></div>
</div>

To, co robi to: daj mi top: 50% i left: 50%, a następnie przekształć (stwórz przestrzeń) na obu osiach X / Y do wartości -50%, w sensie "stwórz przestrzeń lustrzaną".

Jako takie, tworzy to równą przestrzeń na wszystkich 4 punktach div, który jest zawsze pudełkiem (ma 4 boki).

To będzie:

  1. pracować bez znajomości wysokości / szerokości rodzica.
  2. praca nad responsywnym.
  3. pracować na osi X lub Y. Albo jedno i drugie, jak w moim przykładzie.
  4. Nie mogę wymyślić sytuacji, w której to nie zadziała.
 10
Author: Daniel Moss,
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-11-26 18:28:04

Z tego co wiem, Jest to niemożliwe do osiągnięcia dla nieznanej szerokości.

Można - jeśli to działa w Twoim scenariuszu-absolutnie umieścić niewidoczny element o 100% szerokości i wysokości, i mieć element wyśrodkowany tam za pomocą margin: auto i ewentualnie vertical-align. W przeciwnym razie będziesz potrzebował Javascript, aby to zrobić.

 9
Author: Pekka 웃,
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-11-21 22:00:08

Chciałbym dodać do odpowiedzi @bobince:

<body>
    <div style="position: absolute; left: 50%;">
        <div style="position: relative; left: -50%; border: dotted red 1px;">
            I am some centered shrink-to-fit content! <br />
            tum te tum
        </div>
    </div>
</body>

Poprawiono: / / / to sprawia, że poziomy pasek przewijania nie pojawia się z dużymi elementami w wyśrodkowanym div.

<body>
    <div style="width:100%; position: absolute; overflow:hidden;">
        <div style="position:fixed; left: 50%;">
            <div style="position: relative; left: -50%; border: dotted red 1px;">
                I am some centered shrink-to-fit content! <br />
                tum te tum
            </div>
        </div>
    </div>
</body>
 7
Author: Vial,
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-01-28 18:58:14

Heres przydatna wtyczka jQuery do tego celu. Znaleziono Tutaj . Nie sądzę, że jest to możliwe wyłącznie z CSS

/**
 * @author: Suissa
 * @name: Absolute Center
 * @date: 2007-10-09
 */
jQuery.fn.center = function() {
    return this.each(function(){
            var el = $(this);
            var h = el.height();
            var w = el.width();
            var w_box = $(window).width();
            var h_box = $(window).height(); 
            var w_total = (w_box - w)/2; //400
            var h_total = (h_box - h)/2;
            var css = {"position": 'absolute', "left": w_total+"px", "top":
h_total+"px"};
            el.css(css)
    });
};
 6
Author: Ben Shelock,
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-11-21 22:05:35

Moja preferowana metoda centrowania:

position: absolute;
margin: auto;
width: x%
  • absolutne pozycjonowanie elementów bloku
  • margin auto
  • to samo lewo / prawo, góra / dół

JSFiddle here

 4
Author: vp_arth,
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-04-20 06:46:16

Wersja SASS / compass rozwiązania responsywnego powyżej:

#content {
  position: absolute;
  left: 50%;
  top: 50%;
  @include vendor(transform, translate(-50%, -50%));
}
 4
Author: Adam Spence,
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-01 11:16:07

To mi pomogło:

<div class="container><p>My text</p></div>

.container{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
 4
Author: Alan,
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-05-24 12:25:27

Wiem, że już podałem odpowiedź, a moja poprzednia odpowiedź, wraz z innymi, działa dobrze. Ale używałem tego w przeszłości i działa lepiej na niektórych przeglądarkach iw pewnych sytuacjach. Więc pomyślałem, że dam też tę odpowiedź. Nie" edytowałem " mojej poprzedniej odpowiedzi i nie dodałem jej, ponieważ uważam, że jest to całkowicie oddzielna odpowiedź, a dwie, które podałem, nie są ze sobą powiązane.

HTML:

<div id='parent'>
  <div id='child'></div>
</div>

CSS:

#parent {
  display: table;
}
#child {
  display: table-cell;
  vertical-align: middle;
}
 3
Author: Dustin Poissant,
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-01-08 19:29:19
#container
{
  position: relative;
  width: 100%;
  float:left
}
#container .item
{
  width: 50%;
  position: absolute;
  margin: auto;
  left: 0;
  right: 0;
}
 3
Author: Burcu AKCAOGLU,
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-11-25 13:35:03

Działa na dowolnej losowej nieznanej szerokości bezwzględnego elementu, który chcesz mieć w środku elementu kontenera.

Demo

<div class="container">
  <div class="box">
    <img src="https://picsum.photos/200/300/?random" alt="">
  </div>
</div>

.container {
  position: relative;
  width: 100%;
}

.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
 3
Author: lowtechsun,
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-04-10 00:49:04

HTML:

<div class="wrapper">
    <div class="inner">
        content
    </div>
</div>

CSS:

.wrapper {
    position: relative;

    width: 200px;
    height: 200px;

    background: #ddd;
}

.inner {
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    margin: auto;

    width: 100px;
    height: 100px;

    background: #ccc;
}

To i więcej przykładów tutaj

 1
Author: ,
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-14 13:42:13

HTML

<div id='parent'>
  <div id='centered-child'></div>
</div>

CSS

#parent {
  position: relative;
}
#centered-child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto auto;
}

Http://jsfiddle.net/f51rptfy/

 1
Author: Dustin Poissant,
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-16 00:09:50

Jest to sztuczka, którą wymyśliłem, aby uzyskać DIV, który unosi się dokładnie na środku strony. Naprawdę brzydki oczywiście, ale działa we wszystkich

Kropki i kreski

<div style="border: 5 dashed red;position:fixed;top:0;bottom:0;left:0;right:0;padding:5">
    <table style="position:fixed;" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="width:200;border: 5 dashed green;padding:10">
                    Perfectly Centered Content
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

Cleaner

Wow to 5 lat minęło, prawda?
<div style="position:fixed;top:0px;bottom:0px;left:0px;right:0px;padding:5px">
<table style="position:fixed" width="100%" height="100%">
    <tr>
        <td style="width:50%"></td>
        <td style="text-align:center">
            <div style="padding:10px">
                <img src="Happy.PM.png">
                <h2>Stays in the Middle</h2>
            </div>
        </td>
        <td style="width:50%"></td>
    </tr>
</table>

 1
Author: Mr. B,
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-08-21 20:11:06

To rozwiązanie działa, jeśli element ma width i height

.wrapper {
  width: 300px;
  height: 200px;
  background-color: tomato;
  position: relative;
}

.content {
  width: 100px;
  height: 100px;
  background-color: deepskyblue;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}
<div class="wrapper">
  <div class="content"></div>
</div>
 1
Author: Muhammed,
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-09-06 08:32:59

Możesz umieścić obrazek w div I dodać identyfikator div I mieć CSS dla tego div mieć text-align:center

HTML:

<div id="intro_img">

    <img src="???" alt="???">

</div>

CSS:

#intro_img {
    text-align:center;
}
 0
Author: Dworvin Vonstrangle,
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-11-28 15:09:49

#content { margin:0 auto; display:table; float:none;}
<body>
  <div>
    <div id="content">
      I'm the content
    </div>
  </div>
</body>
 0
Author: amit bende,
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-01-02 05:58:04

Proste podejście, które pomogło mi wyśrodkować poziomo blok o nieznanej szerokości:

<div id="wrapper">
  <div id="block"></div>
</div>

#wrapper { position: absolute; width: 100%; text-align: center; }
#block { display: inline-block; }

Właściwość text-align może zostać dodana do zbioru reguł #block, aby wyrównać jej zawartość niezależnie od wyrównania bloku.

To działało na najnowszych wersjach Firefoksa, Chrome, IE, Edge i Safari.
 -1
Author: Terence Bandoian,
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-03-16 04:32:30

Użyłem podobnego rozwiązania:

#styleName {
    position: absolute;
    margin-left: -"X"px;
}

Gdzie " X " jest połową szerokości div, który chcę wyświetlić. Działa dobrze dla mnie we wszystkich przeglądarkach.

 -3
Author: Bartosz,
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-02-04 17:29:15

Staraj się nie używać ciemnej strony CSS. Unikaj stosowania wartości ujemnych dla marginesów. Wiem, że czasami jesteś zmuszony robić okropne rzeczy jak margin-left: -450px, ale prawdopodobnie mógłbyś zrobić coś takiego jak right: 450px. To mój sposób na pracę.

 -3
Author: sebastian,
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-11-28 14:58:53