Pionowe centrowanie div wewnątrz innego div

Chcę wyśrodkować div, który jest dodawany wewnątrz innego div.

<div id="outerDiv">
    <div id="innerDiv">
    </div>
</div>

To jest CSS, którego obecnie używam.

    #outerDiv{
        width: 500px;
        height: 500px;
        position:relative;
    }

    #innerDiv{
        width: 284px;
        height: 290px;
        position:absolute;
        top: 50%;
        left:50%;
        margin-top: -147px;
        margin-left: -144px;
    }

Jak widzisz,podejście, którego teraz używam, zależy od wartości dla szerokości i wysokości innerDiv.Jeśli szerokość / wysokość się zmieni, będę musiał zmodyfikować margin-top i margin-left values.Is czy jest jakieś ogólne rozwiązanie, które mogę użyć, aby wyśrodkować innerDiv zawsze niezależnie od jego wielkości?

Odkryłem, że za pomocą {[6] } można poziomo wyrównać innerDiv do środek./ Align = "left" /

Author: Khánh, 2011-06-27

23 answers

Tl; dr

Vertical align middle działa, ale będziesz musiał użyć table-cell na elemencie rodzica i inline-block na dziecku.

To rozwiązanie nie będzie działać w IE6 & 7. Twoja jest bezpieczniejsza.
Ale skoro otagowałeś swoje pytanie CSS3 i HTML5, pomyślałem, że nie masz nic przeciwko użyciu nowoczesnego rozwiązania.

Rozwiązanie Klasyczne (układ tabeli)

To była moja oryginalna odpowiedź. Nadal działa dobrze i jest rozwiązanie o najszerszym wsparciu. Table-layout wpłynie na wydajność renderowania , więc sugerowałbym użycie jednego z bardziej nowoczesnych rozwiązań.

Oto przykład


Sprawdzone w:

  • FF3. 5+
  • FF4+
  • Safari 5+
  • Chrome 11+
  • IE9+

HTML

<div class="cn"><div class="inner">your content</div></div>

CSS

.cn {
  display: table-cell;
  width: 500px;
  height: 500px;
  vertical-align: middle;
  text-align: center;
}

.inner {
  display: inline-block;
  width: 200px; height: 200px;
}

Nowoczesne rozwiązanie (transform)

Ponieważ transformaty są dość dobrze obsługiwane teraz jest łatwiejszy sposób, aby to zrobić.

CSS

.cn {
  position: relative;
  width: 500px;
  height: 500px;
}

.inner {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%,-50%);
  width: 200px;
  height: 200px;
}

Demo


♥ Moje ulubione nowoczesne rozwiązanie (flexbox)

Zacząłem używać flexbox coraz bardziej its również dobrze obsługiwane teraz Its zdecydowanie najprostszy sposób.

CSS

.cn {
  display: flex;
  justify-content: center;
  align-items: center; 
}

Demo

Więcej przykładów i możliwości: Porównaj wszystkie metody na jednej stronie

 628
Author: meo,
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-27 15:50:16

Innym sposobem osiągnięcia tego poziomego i pionowego centrowania jest:

.Absolute-Center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

(odniesienie )

 106
Author: user700284,
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-07-19 00:24:00

Innym sposobem jest użycie Transform Translate

Zewnętrzny Div musi ustawić swój position na relative lub fixed, a wewnętrzny Div musi ustawić swój position na absolute, top i left do 50% i zastosować transform: translate(-50%, -50%).

div.cn {
    position: relative;
    width: 200px;
    height: 200px;
    background: gray;
    text-align: center;
}

div.inner {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100px;
    height: 100px;
    -webkit-transform: translate(-50%, -50%);  
    transform: translate(-50%, -50%);   
    background: red;
  
}
<div class="cn">
    <div class="inner">
        test
    </div>
</div>

Testowane w:

  • Opera 24.0 (minimum 12.1)
  • Safari 5.1.7 (minimum 4 z prefiksem - webkit -)
  • Firefox 31.0 (minimum 3.6 z prefiksem-moz -, od 16 bez prefiksu)
  • Chrome 36 (minimum 11 z prefiksem-webkit, od 36 bez prefiksu)
  • IE 11, 10 (minimum 9 z prefiksem-ms, od 10 bez prefiksu)
  • więcej przeglądarek, mogę użyć?
 41
Author: Emanuel Ve,
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-12-01 21:17:32

Vertical Align wszystko z tylko 3 linie CSS

HTML

<div class="parent-of-element">

    <div class="element">
        <p>Hello</p>
    </div>

</div>

Najprostszy

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

CSS

.parent-of-element {
   position: relative;
   height: 500px;
   /* or height: 73.61% */
   /* or height: 35vh */
   /* or height: ANY HEIGHT */
}

.element {
  position: absolute;
  top: 50%;

  -webkit-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
          transform: translateY(-50%);
}

Zgodnie z shouldiprefix są to jedyne prefiksy, których potrzebujesz

Możesz również użyć % jako wartości dla właściwości 'height'.rodzic elementu, o ile rodzic elementu ma wysokość lub zawartość, która rozszerza jego rozmiar pionowy.

 38
Author: drjorgepolanco,
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-11-21 16:32:32

Zamiast wiązać się w węzeł z trudnym do napisania i trudnym do utrzymania CSS (który również wymaga starannej weryfikacji między przeglądarkami!) Uważam, że zdecydowanie lepiej zrezygnować z CSS i użyć zamiast tego cudownie prostego HTML 1.0:

<table id="outerDiv" cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td valign="middle" id="innerDiv">
        </td>
    </tr>
</table>

To wszystko, czego chciał oryginalny plakat, jest solidne i łatwe do utrzymania.

 16
Author: Iron Pillow,
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-12 02:59:15

Osobiście wolę sztuczkę polegającą na użyciu ukrytego pseudo elementu, aby rozciągnąć całą wysokość zewnętrznego kontenera i wyrównać go pionowo z inną zawartością. Chris Coyier ma ładny artykuł na temat techniki. http://css-tricks.com/centering-in-the-unknown / Ogromną zaletą tego rozwiązania jest skalowalność. Nie musisz znać wysokości treści ani martwić się o jej wzrost/kurczenie. To rozwiązanie skaluje się:).

Oto gra z wszystkimi CSS, których potrzebujesz i przykład pracy. http://jsfiddle.net/m5sLze0d/

.center:before {
    content: ""; /* Adding Extra Space Above Element */
    display: inline-block;
    height: 100%;
    margin-right: -0.3em;
    vertical-align: middle;
}
.center_element {
    display:inline-block;
    float:none;
    vertical-align:middle;
    white-space:normal;
    text-align:left;
}
 5
Author: Harry Robbins,
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-22 16:31:11

Gdy twoje height nie jest ustawione (auto); możesz dać wewnętrznemu div jakieś wyśrodkowanie (góra i dół), aby było wyśrodkowane pionowo:

<div>
    <div style="padding-top:20px;padding-bottom:20px">
    <!--content-->
    </div>
</div>
 3
Author: Majid,
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-06-01 09:07:17

#outerDiv{
        width: 500px;
        height: 500px;
        position:relative;
        background:grey;
        display:flex;
        justify-content:center;
        align-items:center;
    }

    #innerDiv{
    background:cyan;
        width: 284px;
        height: 290px;

        
    }
<div id="outerDiv">
<div id="innerDiv">Inner Div
</div>
</div>

Możesz to zrobić po prostu dodając wspomniany powyżej styl css. Wszystkiego najlepszego. dla zapytania napisz komentarz

 3
Author: Nishant Singh,
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-09-12 12:56:33

Pionowe centrowanie elementów div wewnątrz innego div

Po prostu ustaw kontener na display:table, a następnie wewnętrzne elementy na display:table-cell. Ustaw height na kontenerze, a następnie Ustaw vertical-align:middle na elementach wewnętrznych. Ma to szeroką kompatybilność aż do czasów IE9.

Zwróć uwagę, że wyrównanie w pionie zależy od wysokości kontenera nadrzędnego.

.cn
{
display:table;
height:80px;
background-color:#555;
}

.inner
{
display:table-cell;
vertical-align:middle;
color:#FFF;
padding-left:10px;
padding-right:10px;
}
<div class="cn">
  <div class="inner">Item 1</div>
  <div class="inner">Item 2</div>
</div>
 3
Author: Volomike,
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-10 04:43:18

Używam następującego rozwiązania od ponad roku, działa również z IE 7 i 8.

<style>
.outer {
    font-size: 0;
    width: 400px;
    height: 400px;
    background: orange;
    text-align: center;
    display: inline-block;
}

.outer .emptyDiv {
    height: 100%;
    background: orange;
    visibility: collapse;
}

.outer .inner {
    padding: 10px;
    background: red;
    font: bold 12px Arial;
}

.verticalCenter {
    display: inline-block;
    *display: inline;
    zoom: 1;
    vertical-align: middle;
}
</style>

<div class="outer">
    <div class="emptyDiv verticalCenter"></div>
    <div class="inner verticalCenter">
        <p>Line 1</p>
        <p>Line 2</p>
    </div>
</div>
 2
Author: Arsh,
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-07-27 19:55:58

To mi pasuje. Można zdefiniować szerokość i wysokość zewnętrznego div.

Tutaj kod:

.outer {
  position: relative;
  text-align: center;
  width: 100%;
  height: 150px; // Any height is allowed, also in %.
  background: gray;
}

.outer > div:first-child {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  background: red;
}
<div class="outer">
  <div class="inner">
    Put here your text or div content!
  </div>
</div>
 2
Author: phlegx,
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-24 21:54:22

Fiddle Link http://jsfiddle.net/dGHFV/2515/>

Try this

   #outerDiv{
        width: 500px;
        height: 500px;
        position:relative;
        border:1px solid red;
    }

    #innerDiv{
        width: 284px;
        height: 290px;
        position:absolute;
        top: 0px;
        left:0px;
        right:0px;
        bottom:0px;
        margin:auto;
        border:1px solid green;
    }
 2
Author: Friend,
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-07-26 09:49:27

Jeśli nadal nie zrozumiałeś po przeczytaniu cudownych odpowiedzi podanych powyżej.

Oto dwa proste przykłady tego, jak można to osiągnąć.

Using display: table-cell

.wrapper {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  width: 400px;
  height: 300px;
  border: 1px solid #555;
}

.container {
  display: inline-block;
  text-align: left;
  padding: 20px;
  border: 1px solid #cd0000;
}
<div class="wrapper">
  <div class="container">
    Center align a div using "<strong>display: table-cell</strong>"
  </div>
</div>

Using flex-box (display: flex)

.wrapper {
  display: flex;
  justify-content: center;
  width: 400px;
  height: 300px;
  border: 1px solid #555;
}

.container {
  align-self: center;
  padding: 20px;
  border: 1px solid #cd0000;
}
<div class="wrapper">
    <div class="container">
        Centering a div using "<strong>display: flex</strong>"
    </div>
</div>

Uwaga: Przed użyciem wyżej wymienionych implementacji sprawdź zgodność display: table-cell i flex w przeglądarce.

 2
Author: shivamsupr,
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-16 13:57:46

Tutaj wpisz opis obrazka 100% działa

.div1{
  height: 300px;
  background: red;
  width: 100%;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -ms-flex-align: center;
  -webkit-align-items: center;
  -webkit-box-align: center;
  align-items: center;
}
.div2{
  background: green;
  height: 100px;
  width: 100%;
}

    <div class="div1">
      <div class="div2">
      sdfd
      </div>
    </div>

Https://jsfiddle.net/Mangesh1556/btn1mozd/4/

 2
Author: Mangesh Jadhav,
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-17 06:48:24

Dla innerdiv,które nie określają wartości wysokości, nie ma czystego rozwiązania css, które pozwoliłoby na wyśrodkowanie go w pionie.rozwiązaniem javascript może być get the innerdiv ' s offsetHeight,a następnie obliczyć styl.marginTop.

 1
Author: james li,
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
2011-06-27 08:30:26

Możesz to zrobić za pomocą prostego bloku javascript (jQuery).

CSS:

#outerDiv{
    height:100%;
}

Javascript :

<script type="text/javascript">
    $(document).ready(function () {
        $("#innerDiv").css('top', ($(window).height() - $("#content").height()) / 2);
    });
</script>
 1
Author: Ghanesh MV,
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-22 18:51:05

Spróbuj wyrównać Wewnętrzny element tak:

top: 0;
bottom: 0;
margin: auto;
display: table;

I oczywiście:

position: absolute;
 1
Author: VonAxt,
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-10-21 12:42:52

Możesz wyśrodkować div pionowo i poziomo w CSS za pomocą flex;

#outerDiv{
width: 500px;
    height: 500px;
    position:relative;
    border:1px solid #000;
    margin:0 auto;
    display: flex;
    -webkit-flex-direction: row;
    flex-direction: row;
    -webkit-align-items: center;
    align-items: center;
    -webkit-justify-content: center;
    justify-content: center;

    }

#innerDiv{
    width: 284px;
    height: 290px;
    border:1px solid #eee;

}

A drugi jest następujący;

    #outerDiv{
        width: 500px;
        height: 500px;
        position:relative;
        border:1px solid #000;
        }

        #innerDiv{
        max-width: 300px;
        height: 200px;
        background-color: blue;
        position:absolute; 
        left:0;
        right:0;
        top:0;
        bottom:0;
        margin:auto;
        border:1px solid #000;
        border-radius:4px;
    }

I wynikowy HTML:

    <div id="outerDiv">
        <div id="innerDiv"></div>
    </div>
 1
Author: Tariq Javed,
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-03-28 21:44:08

To będzie działać z powrotem do IE6!

<!DOCTYPE html> jest wymagane również na IE6! [wymusi również domyślny tryb ścisły IE6 ].

( Oczywiście kolorowanie pudełka jest tylko w celach demonstracyjnych )

    #outer{
        width: 205px;
        height: 205px;
        margin: auto; 
        text-align: center;
    }
    #inner{
        text-align: left;
        vertical-align: middle;
        width: 120px;
        height: 120px;
        display: inline-block;
   
    }
    #center{
        height: 100%; width:0px;
        vertical-align: middle;
        display: inline-block;
    }
    div {background: rgba(0,128,255,.6)}
<div id=outer>
    <div id=center></div><div id=inner> The inner DIV
    </div>
</div>
 1
Author: Bekim Bacaj,
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-08-15 08:32:51

Text align-center na elemencie nadrzędnym, display inline-block na elemencie podrzędnym. To wyśrodkuje wszystko. Myślę, że nazywa się to "float block".

<div class="outer">
 <div class="inner"> some content </div>
</div><!-- end outer -->

<style>
div.outer{
 width: 100%;
 text-align: center;
}
div.inner{
 display: inline-block;
 text-align: left
}
</style>

Jest to również dobra alternatywa dla float ' s, powodzenia!

 0
Author: user3943543,
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-03-12 17:50:14

Pionowe centrowanie div wewnątrz innego div

#outerDiv{
  width: 500px;
  height: 500px;
  position:relative;
  
  background-color: lightgrey;  
}

#innerDiv{
  width: 284px;
  height: 290px;
  
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%); /* IE 9 */
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */	
  
  background-color: grey;
}
<div id="outerDiv">
  <div id="innerDiv"></div>
</div>
 0
Author: antelove,
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-09-25 07:09:35

Do center align zarówno w pionie jak i w poziomie:

#parentDiv{
    display:table;
    text-align:center;
}

#child {
     display:table-cell;
     vertical-align:middle;
}
 0
Author: Bhimashankar Sutar,
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-28 13:32:38

Wiem, że to pytanie powstało rok temu... W każdym razie dzięki CSS3 możesz łatwo wyrównać div w div (przykład tam http://jsfiddle.net/mcSfe/98/)

<div style="width: 100px; height: 100px">
<div>
Go to Hell!
</div>
</div>

div
{
display:-moz-box;
-moz-box-align:center;
} 
 -6
Author: godlark,
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-06-06 22:46:29