CSS wyśrodkuj tekst (poziomo i pionowo) wewnątrz bloku div

Mam div ustawione na display:block. (90px height i width) i mam w środku 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?
 607
Author: CyanCoding, 2011-04-18

24 answers

Jeśli jest to jeden wiersz 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 wszystko. Jeśli może to być wiele linii, to jest to nieco bardziej skomplikowane. Ale są rozwiązania na http://pmob.co.uk / Szukaj "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 2016 / 2017:

Może być więcej często robione z transform i działa dobrze nawet w starszych przeglądarkach, takich jak IE10 i IE11. Może obsługiwać wiele linii tekstu:

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

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

Aby obkurczyć szerokość:

W powyższym rozwiązaniu zastosowano stałą szerokość dla obszaru zawartości. Aby użyć szerokości folii termokurczliwej, użyj

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

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

Próbowałem flexbox, ale nie był tak szeroko obsługiwany, jak by się włamał niektóre starsze wersje IE, takie jak IE10.

 1001
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
2017-02-02 13:27:05

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

 51
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 css dla tego div. tylko komórki tabeli obsługują vertical-align:middle;, ale możesz dać tę definicję [table-cell] do div..

Przykład na żywo 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
}
 25
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
2011-04-18 13:28:13

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/

 12
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
2015-08-23 08:48:21

Możesz wypróbować bardzo prosty kod do tego

  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>

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

 11
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
2016-12-16 10:07:37

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>
 8
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
2017-09-11 12:41:27

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>
 7
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
2017-07-05 12:54:03
#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
}
 4
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
2015-02-22 03:47:32
<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

Jednym z najlepszych sposobów jest użycie właściwości flex w parent div I dodanie właściwości margin:auto do znacznik elementu

.parent{
    display: flex;
    flex-direction: column;
    flex: 1;
    height:100%;
}

p{
    margin:auto;
}
 3
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
2018-08-06 06:31:51

div {
  height: 90px;
  line-height: 90px;
  text-align: center;
  border: 2px dashed #f69c55;
}
<div>
  Hello World!
</div>
 2
Author: Debasis Paul,
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-02-20 03:33:02

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, a następnie 50% fi. / Align = "center" bgcolor = "# e0ffe0 " / cesarz Chin / / align = center / ]}

 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
2016-12-05 20:45:24

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
<!DOCTYPE html>
<html>
  <head>
    <style>
      .container{
        height:450px;
        background:#f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-align: center;
        justify-content: center;
        width: 100%;
      }
      p{
      font-size:24px;}
    </style>
  </head>
  <body>
    <div class="container">
      <p>hello world</p>
    </div>
  </body>
</html>
 0
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
2017-03-17 05:21:21
<!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>
 0
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
2017-03-17 05:25:10

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 można określić wielkości dzielnika w px lub %.(gdy dzielnik 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 pionowym centrowaniu podczas "justify-content: center" spowoduje wyśrodkowanie w poziomie.

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

 0
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
2017-03-22 06:15:14

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

.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>
 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-10-12 09:32:51

To zadziałało dla mnie

.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
2018-02-02 11:15:16

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> 
 -1
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
<!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> 
 -2
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
footer {
    width: 100%;
    height: 80px;
    position: absolute;
    bottom: 0;
    left: 0;
}
 -12
Author: Kyle Cabral,
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 02:55:36