Wyśrodkować element o pozycji "absolutnej" i niezdefiniowanej szerokości w CSS?

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;
}
Jak mogę to zrobić?
Author: Jesse Nickles, 2009-11-21

30 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>
 1418
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>
 1898
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 dzieciach i rodzicem. 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%);

 886
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
2020-06-20 09:12:55

Chciałem tylko dodać jeśli ktoś chce to zrobić z pojedynczym znacznikiem div to tutaj jest 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.

 49
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
2020-06-20 09:34:58

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/

Został przetestowany w przeglądarkach Google Chrome, Firefox i Internet Explorer 8.
 36
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
2020-06-20 09:52:32

To działa dla pionu i poziomu:

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

I jeśli chcesz utworzyć element centrum rodzica, ustaw pozycję względem rodzica:

#parentElement{
    position: relative
}
  • Dla pozycji vertical center align, Ustaw wysokość elementu. Dzięki Raulowi.

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

 32
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
2020-06-20 10:02:19
<div style='position:absolute; left:50%; top:50%; transform: translate(-50%, -50%)'>
    This text is centered.
</div>

Spowoduje to wyśrodkowanie wszystkich obiektów wewnątrz div o typie pozycji static lub relative.

 27
Author: Utkarsh Tyagi,
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
2020-06-20 13:41:50

Rozwiązanie responsywne

Zakładając, że element w div, jest innym div...

To rozwiązanie działa dobrze:

<div class="container">
  <div class="center"></div>
</div>

Kontener może mieć dowolny rozmiar (musi być pozycja względna):

.container {
    position: relative; /* Important */
    width: 200px; /* Any width */
    height: 200px; /* Any height */
    background: red;
}

Element (div ) może również mieć dowolny rozmiar (musi być mniejszy niż kontener):

.center {
    position: absolute; /* Important */
    top: 50%; /* Position Y halfway in */
    left: 50%; /* Position X halfway in */
    transform: translate(-50%,-50%); /* Move it halfway back(x,y) */
    width: 100px; /* Any width */
    height: 100px; /* Any height */
    background: blue;
}

Wynik będzie wyglądał tak. Uruchom fragment kodu:

.container {
    position: relative;
    width: 200px;
    height: 200px;
    background: red;
}

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100px;
    height: 100px;
    background: blue;
}
<div class="container">
    <div class="center"></div>
</div>
Uznałem to za bardzo pomocne.
 26
Author: RealMJDev,
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
2020-06-20 10:28:57

Jeśli musisz wyśrodkować poziomo i pionowo:

left: 50%;
top: 50%;
transform: translate(-50%, -50%);
 24
Author: michal.jakubeczy,
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
2019-02-15 08:50:03

Szukając rozwiązania, otrzymałem poprzednie odpowiedzi i mogłem uczynić treść wyśrodkowaną odpowiedzią Matthiasa Weilera , ale używając text-align:

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

To działało z Google Chrome i Firefox.

 23
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
2020-06-20 09:44:49

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>

Mówi się, że 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 czterech punktach div, która jest zawsze pudełko (ma cztery strony).

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.
 15
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
2020-06-20 10:14:54

To jest mieszanka innych odpowiedzi, które zadziałały dla nas:

.el {
   position: absolute;
   top: 50%;
   margin: auto;
   transform: translate(-50%, -50%);
}
 14
Author: Crashalot,
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
2019-08-01 10:36:50

Działa to na dowolnej, 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;
}
 14
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
2020-06-20 10:17:22

Flexbox może być użyty do wyśrodkowania bezwzględnego div.

display: flex;
align-items: center;
justify-content: center;

.relative {
  width: 275px;
  height: 200px;
  background: royalblue;
  color: white;
  margin: auto;
  position: relative;
}

.absolute-block {
  position: absolute;
  height: 36px;
  background: orange;
  padding: 0px 10px;
  bottom: -5%;
  border: 1px solid black;
}

.center-text {
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 1px 2px 10px 2px rgba(0, 0, 0, 0.3);
}
<div class="relative center-text">
  Relative Block
  <div class="absolute-block center-text">Absolute Block</div>
</div>
 13
Author: Dhaval Jardosh,
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
2020-06-20 10:21:52

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ć.

 8
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
2020-06-20 09:32:19

Chciałbym dodać do odpowiedź 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
2020-06-20 09:41:37

Oto przydatna wtyczka jQuery do tego celu. Znalazłem to Tutaj . Nie sądzę, żeby to było 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)
    });
};
 5
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
2020-06-20 09:33:40

Sass/Kompas wersja poprzedniego rozwiązania responsywnego :

#content {
  position: absolute;
  left: 50%;
  top: 50%;
  @include vendor(transform, translate(-50%, -50%));
}
 5
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
2020-06-20 10:08:52

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;
}
 5
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
2020-06-20 10:09:54

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 jest tutaj .

 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
2020-06-20 09:53:59
#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
2020-06-20 10:00:33

HTML:

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

CSS:

#parent {
  display: table;
}
#child {
  display: table-cell;
  vertical-align: middle;
}

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.

 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
2020-06-20 10:05:57

Przyjęte rozwiązanie tego pytania nie zadziałało w mojej sprawie...

Robię podpis dla niektórych obrazów i rozwiązałem go za pomocą tego:

top: 0;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;

display: flex;
align-items: center;

figure {
    position: relative;
    width: 325px;
    display: block
}


figcaption{
    position: absolute;
    background: #FFF;
    width: 120px;
    padding: 20px;

    -webkit-box-shadow: 0 0 30px grey;
    box-shadow: 0 0 30px grey;
    border-radius: 3px;
    display: block;

    top: 0;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;

    display: flex;
    align-items: center;
}
<figure>
    <img  src="https://picsum.photos/325/600">
    <figcaption>
        But as much
    </figcaption>
</figure>
 3
Author: Marcogomesr,
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
2020-06-20 10:19:16

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/

 2
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

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: Mo.,
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
.center {
  position: absolute
  left: 50%;
  bottom: 5px;
}

.center:before {
    content: '';
    display: inline-block;
    margin-left: -50%;
}
 1
Author: AndreyP,
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
2019-01-24 10:34:49

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

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, te pięć 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>
</div>
 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
2020-06-20 09:47:42

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: Peter Mortensen,
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
2020-06-20 09:51:14

#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

Żadne z rozwiązań nie zadziałało na mnie, ponieważ nie chciałem zmieniać stylizacji elementu kontenera / owijarki. Ten kod zadziałał dla mnie:

position: absolute;
left: 50%;
margin-left: -50px;
top: 50%;
margin-top: -50px;
 0
Author: Nick.K,
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
2020-01-23 19:35:47