Jak wyśrodkować tekst (poziomo i pionowo) wewnątrz bloku div?

Mam div ustawione na display:block (90px height i width), a w środku mam jakiś tekst.

Chcę, aby tekst był wyrównany w środku zarówno w pionie, jak i w poziomie.

Próbowałem text-align:center, ale nie robi to części poziomej, więc próbowałem vertical-align:middle, ale nie zadziałało.

Jakieś pomysły?
 965
Author: isherwood, 2011-04-18

27 answers

Jeśli jest to jedna linijka tekstu i / lub obrazu, to jest to łatwe do zrobienia. Wystarczy użyć:

text-align: center;
vertical-align: middle;
line-height: 90px;       /* The same as your div height */

To jest to. Jeśli może to być wiele linii, to jest to nieco bardziej skomplikowane. Ale są rozwiązania na http://pmob.co.uk / . poszukaj "vertical align".

Ponieważ mają tendencję do hacków lub dodawania skomplikowanych divów... Zwykle używam tabeli z pojedynczą komórką, aby to zrobić... żeby było jak najprościej.


Aktualizacja na rok 2020:

Unless you need make it pracuj na wcześniejszych przeglądarkach, takich jak Internet Explorer 10, możesz użyć flexbox. Jest to szeroko obsługiwane przez wszystkie obecne główne przeglądarki . Kontener musi być określony jako elastyczny kontener, wraz z centrowaniem wzdłuż jego głównej i poprzecznej osi:

#container {
  display: flex;
  justify-content: center;
  align-items: center;
}

Aby określić stałą szerokość dla dziecka, która jest nazywana "elementem flex":

#content {
  flex: 0 0 120px;
}

Przykład: http://jsfiddle.net/2woqsef1/1/

Aby zmniejszyć zawartość, jest jeszcze prostsze: tylko usuń linię flex: ... z elementu flex, a zostanie ona automatycznie zawinięta w folię termokurczliwą.

Przykład: http://jsfiddle.net/2woqsef1/2/

Powyższe przykłady zostały przetestowane na głównych przeglądarkach, w tym MS Edge i Internet Explorer 11.

Jedna uwaga techniczna Jeśli chcesz ją dostosować: wewnątrz elementu flex, ponieważ ten element flex nie jest sam w sobie kontenerem flex, stary sposób CSS non-flexbox działa zgodnie z oczekiwaniami. Jeśli jednak dodasz dodatkowy element flex do obecny kontener flex, dwa elementy flex będą umieszczone poziomo. Aby umieścić je pionowo, dodaj flex-direction: column; do pojemnika flex. Tak działa między kontenerem flex a jego potomnymi elementami .

Istnieje alternatywna metoda centrowania: nie określając center dla rozkładu na głównej i poprzecznej osi dla kontenera flex, ale zamiast tego określ margin: auto na elemencie flex, aby zajął wszystkie dodatkowe miejsce we wszystkich czterech kierunkach, równomiernie rozmieszczone marginesy sprawią, że element flex wyśrodkuje się we wszystkich kierunkach. Działa to z wyjątkiem sytuacji, gdy istnieje wiele elementów flex. Również ta technika działa na MS Edge, ale nie na Internet Explorer 11.


Aktualizacja na rok 2016 / 2017:

Można to zrobić częściej za pomocą transform i działa dobrze nawet w starszych przeglądarkach, takich jak Internet Explorer 10 i Internet Explorer 11. Może obsługiwać wiele linii tekstu:

position: relative;
top: 50%;
transform: translateY(-50%);

Przykład: https://jsfiddle.net/wb8u02kL/1/

Aby zmniejszyć-owinąć Szerokość:

W powyższym rozwiązaniu zastosowano stałą szerokość obszaru zawartości. Aby użyć szerokości owiniętej w folię termokurczliwą, użyj

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

Przykład: https://jsfiddle.net/wb8u02kL/2/

Jeśli potrzebne jest wsparcie dla Internet Explorera 10, to flexbox nie będzie działać i metoda powyżej i metoda line-height będą działać. W przeciwnym razie flexbox wykonałby to zadanie.

 1581
Author: nonopolarity,
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-03-11 08:07:16

Popularne techniki od 2014 roku:


  • Podejście 1 - transform translateX/translateY:

    Przykład Tutaj / Przykład Pełnoekranowy

    W obsługiwanych przeglądarkach (większość z nich), można użyć top: 50%/left: 50% w połączeniu z translateX(-50%) translateY(-50%) aby dynamicznie wyśrodkować element w pionie/poziomie.

    .container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-50%);
    }
    

  • Podejście 2-Metoda Flexbox:

    Przykład Tutaj / Przykład Pełnoekranowy

    W obsługiwanych przeglądarkach Ustaw display docelowego elementu na flex i użyj align-items: center do centrowania pionowego i justify-content: center do centrowania poziomego. Po prostu nie zapomnij dodać przedrostków dostawcy dla dodatkowej obsługi przeglądarki (zobacz przykład).

    html, body, .container {
        height: 100%;
    }
    .container {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    

  • Podejście 3 - table-cell/vertical-align: middle:

    Przykład Tutaj / Pełny Ekran Przykład

    W niektórych przypadkach należy upewnić się, że html/body Wysokość elementu jest ustawiona na 100%.

    Dla wyrównania pionowego, Ustaw element nadrzędny width/height do 100% i dodać display: table. Następnie dla elementu potomnego Zmień display na table-cell i dodaj vertical-align: middle.

    Do poziomego centrowania można dodać text-align: center, aby wyśrodkować tekst i inne elementy potomne inline. Alternatywnie możesz użyć margin: 0 auto zakładając, że element jest block poziom.

    html, body {
        height: 100%;
    }
    .parent {
        width: 100%;
        height: 100%;
        display: table;
        text-align: center;
    }
    .parent > .child {
        display: table-cell;
        vertical-align: middle;
    }
    

  • Podejście 4-absolutnie ustawione 50% od góry z przesunięciem:

    Przykład Tutaj / Przykład Pełnoekranowy

    To podejście zakłada, że tekst ma znaną wysokość-w tym przypadku 18px. Po prostu absolutnie umieść element 50% od góry, względem elementu nadrzędnego. Użyj ujemnej wartości margin-top, która jest połową znanej wysokości elementu, w tym przypadku - -9px.

    html, body, .container {
        height: 100%;
    }
    .container {
        position: relative;
        text-align: center;
    }
    .container > p {
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        margin-top: -9px;
    }
    

  • Podejście 5-metoda line-height (najmniej elastyczna - nie sugerowana):

    Przykład Tutaj

    W niektórych przypadkach element nadrzędny będzie miał stałą wysokość. Aby wyśrodkować pionowo, wystarczy ustawić na elemencie potomnym wartość line-height równą stałej wysokości elementu nadrzędnego.

    Chociaż to rozwiązanie będzie działać w niektórych przypadkach, warto zauważyć, że nie będzie działać, gdy istnieje wiele linie tekstu - jak to .

    .parent {
        height: 200px;
        width: 400px;
        text-align: center;
    }
    .parent > .child {
        line-height: 200px;
    }
    

Metody 4 i 5 nie są najbardziej wiarygodne. Wybierz jedną z pierwszych trzech.
 467
Author: Josh Crozier,
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-09-12 01:28:24

Użycie flexbox / CSS:

<div class="box">
    <p>&#x0D05;</p>
</div>

CSS:

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

Zaczerpnięte z Quick Tip: najprostszy sposób na wyśrodkowanie elementów w pionie i poziomie

 83
Author: Vinod,
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-10 03:25:16

Dodaj linię display: table-cell; do swojej zawartości CSS dla tego div.

Tylko komórki tabeli obsługują vertical-align: middle;, ale możesz podać definicję [table-cell] do div...

Przykład na żywo jest tutaj: http://jsfiddle.net/tH2cc/

div{
    height: 90px;
    width: 90px;
    text-align: center;
    border: 1px solid silver;
    display: table-cell; // This says treat this element like a table cell
    vertical-align:middle; // Now we can center vertically like in a TD
}
 30
Author: FatherStorm,
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-07-01 22:22:16

Daj tę klasę CSS do docelowego

:

.centered {
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  background: red; /* Not necessary just to see the result clearly */
}
<div class="centered">This text is centered horizontally and vertically</div>
 20
Author: Aminu Kano,
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-07-01 22:36:35

Możesz wypróbować bardzo prosty kod:

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

.box{
  height: 90px;
  width: 90px;
  background: green;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="box">
  Lorem
</div>

Codepen link: http://codepen.io/santoshkhalse/pen/xRmZwr

 18
Author: Santosh Khalse,
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-07-01 22:26:47

Zawsze używam następującego CSS dla kontenera, aby wyśrodkować jego zawartość poziomo i pionowo.

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;

-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;

Zobacz go w akcji tutaj: https://jsfiddle.net/yp1gusn7/

 17
Author: Kent Munthe Caspersen,
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-07-01 22:24:05

Możesz użyć właściwości flex w rodzicu div i dodaj Właściwość margin:auto do elementów potomnych:

.parent {
    display: flex;
    /* You can change this to `row` if you want the items side by side instead of stacked */
    flex-direction: column;
}

/* Change the `p` tag to what your items child items are */
.parent p {
    margin: auto;
}

Możesz zobaczyć więcej opcji flex tutaj: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

 11
Author: user3021146,
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-10-10 20:10:29

Podejście 1

div {
  height: 90px;
  line-height: 90px;
  text-align: center;
  border: 2px dashed #f69c55;
}
<div>
  Hello, World!!
</div>

Podejście 2

div {
  height: 200px;
  line-height: 200px;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Haec et tu ita posuisti, et verba vestra sunt. Non enim iam stirpis bonum quaeret, sed animalis. </span>
</div>

Podejście 3

div {
  display: table;
  height: 100px;
  width: 100%;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: table-cell;
  vertical-align: middle;
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
 9
Author: shubham agrawal,
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-07-01 22:34:59
# Parent
{
  display:table;
}

# Child
{
  display: table-cell;
  width: 100%; // As large as its parent to center the text horizontally
  text-align: center;
  vertical-align: middle; // Vertically align this element on its parent
}
 5
Author: Narcisse Doudieu Siewe,
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-07-01 22:23:24
<div class="small-container">
    <span>Text centered</span>
</div>

<style>
.small-container {
    width:250px;
    height:250px;
    border:1px green solid;
    text-align:center;
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
.small-container span{
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
</style>
 4
Author: Arunkumar Maha,
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-12-09 03:47:50

div {
  height: 90px;
  line-height: 90px;
  text-align: center;
  border: 2px dashed #f69c55;
}
<div>
  Hello, World!!
</div>
 4
Author: debasispaul,
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-07-01 22:39:15

Siatka

.center {
    display: grid;
    justify-items: center;
    align-items: center;
}

.center {
    display: grid;
    justify-items: center;
    align-items: center;
}

.box {
    width: 200px;
    height: 100px;
    background: red;
}
<div class="box center">My text</div>
 4
Author: Kamil Kiełczewski,
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-04-06 18:06:07

2020 sposób

.parent{ 
  display: grid;
  place-items: center;
}
 4
Author: readytohackk,
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-07-24 04:06:23

.cell-row {display: table; width: 100%; height: 100px; background-color: lightgrey; text-align: center}
.cell {display: table-cell}
.cell-middle {vertical-align: middle}
<div class="cell-row">
  <div class="cell cell-middle">Center</div>
</div>
 2
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-10-12 09:32:51

Możesz wypróbować następujące metody:

  1. Jeśli masz jedno słowo lub jedno zdanie liniowe, poniższy kod może załatwić sprawę.

    Umieść tekst wewnątrz znacznika div i nadaj mu id. Zdefiniuj następujące właściwości dla tego identyfikatora.

    id-name {
      height: 90px;
      line-height: 90px;
      text-align: center;
      border: 2px dashed red;
    }
    

    Uwaga: upewnij się, że właściwość line-height jest taka sama jak wysokość podziału.

    Obraz

    Ale jeśli zawartość jest więcej niż jednym słowem lub linią, to nie działa. Również, czasami nie będzie można określić rozmiaru podziału w px lub % (gdy podział jest naprawdę mały i chcesz, aby zawartość była dokładnie pośrodku).

  2. Aby rozwiązać ten problem, możemy wypróbować następującą kombinację właściwości.

    id-name {
      display: flex;
      justify-content: center;
      align-items: center;
      border: 2px dashed red;
    }
    

    Obraz

    Te 3 linie kodu ustawiają zawartość dokładnie w środku podziału(niezależnie od wielkości wyświetlacza). "align-items: center" pomaga w centrowaniu pionowym podczas gdy "justify-content: center" będzie to wyśrodkowane poziomo.

    Uwaga: Flex nie działa we wszystkich przeglądarkach. Upewnij się, że dodałeś odpowiednie prefiksy dostawcy, aby uzyskać dodatkową obsługę przeglądarki.

 2
Author: Clinton Roy,
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-07-01 22:31:36

Dodaj następujący kod w rodzicu div

 display: grid;
 place-items: center;
 2
Author: Codemaker,
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-08-18 13:42:27

To działa dla mnie (przetestowane OK!):

HTML:

<div class="mydiv">
    <p>Item to be centered!</p>
</div>

CSS:

.mydiv {
    height: 100%; /* Or other */
    position: relative;
}

.mydiv p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%); /* To compensate own width and height */
}

Możesz wybrać inne wartości niż 50%. Na przykład, 25% do centrum na 25% rodzica.

 1
Author: XPloRR,
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-07-01 22:26:04
<!DOCTYPE html>
<html>
  <head>
    <style>
      .maindiv {
        height: 450px;
        background: #f8f8f8;
        display: -webkit-flex;
        align-items: center;
        justify-content: center;
      }
      p {
        font-size: 24px;
      }
    </style>
  </head>

  <body>
    <div class="maindiv">
      <h1>Title</h1>
    </div>
  </body>
</html>
 1
Author: Nikit Barochiya,
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-07-01 22:30:04

Dla mnie to było najlepsze rozwiązanie:

HTML:

 <div id="outer">  
     <img src="logo.png">
 </div>

CSS:

#outer {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}
 1
Author: Bence Végert,
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-14 09:58:48

Regulacja wysokości linii, aby uzyskać wyrównanie pionowe.

line-height: 90px;
 0
Author: Abhay,
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-19 10:11:14

To powinna być właściwa odpowiedź. Najczystsze i najprostsze:

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
 0
Author: Mike Barwick,
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-15 20:01:57

Zastosuj styl:

position: absolute;
top: 50%;
left: 0;
right: 0;

Twój tekst będzie wyśrodkowany niezależnie od jego długości.

 0
Author: techloris_109,
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-06 19:24:59

To mi pomogło:

.center-stuff{
    text-align: center;
    vertical-align: middle;
    line-height: 230px; /* This should be the div height */
}
 0
Author: Ger Mc,
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-07-01 22:38:31
<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>
        <div style ="text-align: center;">Center horizontal text</div>
        <div style ="position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%);">Center vertical text</div>
    </body>
</html> 
 -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
2018-07-07 14:00:49

Naprawdę prosty kod, który działa dla mnie! tylko jedna linia i twój tekst będzie wyśrodkowany poziomo.

.center-horizontally{
  justify-content: center;
}

<Card.Footer className="card-body-padding center-horizontally">
  <label className="support-expand-text-light">Call or email Customer Support to change</label>
</Card.Footer>

Wyjście wygląda tak:

proszę zagłosować na tę odpowiedź, jeśli to działa tylko po to, aby poświęcić trochę czasu deweloperom szukającym łatwych rozwiązań. Dzięki! :)

 -1
Author: Jeanne vie,
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-03-05 02:42:21

Wypróbuj poniższy przykład. Dodałem przykłady dla każdej kategorii: pozioma i pionowa

<!DOCTYPE html>
<html>
    <head>
        <style>
            #horizontal
            {
                text-align: center;
            }
            #vertical
            {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translateX(-50%) translateY(-50%);
            }
         </style>
    </head>
    <body>
         <div id ="horizontal">Center horizontal text</div>
         <div id ="vertical">Center vertical text</div>
    </body>
</html> 
 -2
Author: Amir Md Amiruzzaman,
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-07-04 20:12:54