¿Cómo puedo centrar verticalmente el texto con CSS?


Tengo un elemento div que contiene texto, y quiero alinear el contenido de este div verticalmente al centro.

Aquí está mi estilo div:

#box {
  height: 170px;
  width: 270px;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}
<div id="box">
  Lorem ipsum dolor sit
</div>

¿Cuál es la mejor manera de hacer esto?

Author: Tom Aranda, 2012-01-15

30 answers

Puedes probar este enfoque básico:

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

Sin embargo, solo funciona para una sola línea de texto, porque establecemos la altura de la línea a la misma altura que el elemento box que contiene.


Un enfoque más versátil

Esta es otra forma de alinear el texto verticalmente. Esta solución funcionará para una sola línea y varias líneas de texto, pero todavía requiere un contenedor de altura fija:

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>

El CSS solo mide el <div>, verticalmente el centro alinea el <span> estableciendo la altura de la línea de <div> igual a su altura, y hace que el <span> sea un bloque en línea con vertical-align: middle. Luego establece la altura de la línea de nuevo a la normal para el <span>, por lo que su contenido fluirá naturalmente dentro del bloque.


Visualización de la tabla de simulación

Y aquí hay otra opción, que puede no funcionar en navegadores más antiguos que no admiten display: table y display: table-cell (básicamente solo Internet Explorer 7). Usando CSS simulamos el comportamiento de la tabla (ya que las tablas soportan la alineación vertical), y el HTML es el mismo que el segundo ejemplo:

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>

Usando el posicionamiento absoluto

Esta técnica utiliza un elemento absolutamente posicionado estableciendo arriba, abajo, izquierda y derecha a 0. Se describe con más detalle en un artículo en la revista Smashing, Centrado Horizontal Y Vertical Absoluto En CSS.

 2521
Author: Michiel van Oosterhout,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-11 15:37:13

Otra forma (no mencionada aquí todavía) es con Flexbox.

Simplemente agregue el siguiente código al elemento container :

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

Flexbox demo 1

.box {
  height: 150px;
  width: 400px;
  background: #000;
  font-size: 24px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  padding: 0 20px;
  margin: 20px;
  display: flex;
  justify-content: center;
  /* align horizontal */
  align-items: center;
  /* align vertical */
}
<div class="box">
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
</div>

Alternativamente, en lugar de alinear el contenido a través del contenedor , flexbox también puede centrar el elemento a flex con un margen automático cuando solo hay un elemento flex en el contenedor flex (como el ejemplo dado en la pregunta anterior).

Así que para centrar el elemento flexible tanto horizontal como verticalmente, simplemente colóquelo con margin:auto

Flexbox Demo 2

.box {
  height: 150px;
  width: 400px;
  background: #000;
  font-size: 24px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  padding: 0 20px;
  margin: 20px;
  display: flex;
}
.box span {
  margin: auto;
}
<div class="box">
  <span>margin:auto on a flex item centers it both horizontally and vertically</span> 
</div>

NB: Todo lo anterior se aplica a los elementos de centrado mientras se colocan en filas horizontales. Este es también el comportamiento predeterminado, porque por defecto el valor para flex-direction es row. Sin embargo, si los elementos flexibles deben estar dispuestos en columnas verticales , entonces flex-direction: column debe establecerse en el contenedor para establecer el eje principal como columna y, además, las propiedades justify-content y align-items ahora funcionan al revés con justify-content: center centrado verticalmente y align-items: center centrado horizontalmente)

flex-direction: column demo

.box {
  height: 150px;
  width: 400px;
  background: #000;
  font-size: 18px;
  font-style: oblique;
  color: #FFF;
  display: flex;
  flex-direction: column;
  justify-content: center;
  /* vertically aligns items */
  align-items: center;
  /* horizontally aligns items */
}
p {
  margin: 5px;
  }
<div class="box">
  <p>
    When flex-direction is column...
  </p>
  <p>
    "justify-content: center" - vertically aligns
  </p>
  <p>
    "align-items: center" - horizontally aligns
  </p>
</div>

Un buen lugar para comenzar con Flexbox para ver algunas de sus características y obtener sintaxis para el máximo soporte del navegador es flexyboxes

Además, el soporte del navegador hoy en día es muy bien: caniuse

Para la compatibilidad entre navegadores para display: flex y align-items, puede usar lo siguiente:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
 1003
Author: Danield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-13 22:22:52

Puede hacer esto fácilmente agregando la siguiente pieza de código CSS:

display: table-cell;
vertical-align: middle;

Eso significa que su CSS finalmente se ve como:

#box {
  height: 90px;
  width: 270px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  margin-top: 20px;
  margin-left: 5px;
  display: table-cell;
  vertical-align: middle;
}
<div id="box">
  Some text
</div>
 114
Author: Ariful Islam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-12 08:09:02

Para referencia y para agregar una respuesta más simple:

CSS puro:

.vertical-align {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

O como mezcla SASS / SCSS:

@mixin vertical-align {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

Utilizar por:

.class-to-center {
    @include vertical-align;
}

Por La entrada de blog de Sebastian Ekström Vertical alinear cualquier cosa con solo 3 líneas de CSS:

Este método puede hacer que los elementos sean borrosos debido a que el elemento se coloca en un "medio píxel". Una solución para esto es establecer su elemento padre en preserve-3d. Como sigue:

.parent-element {
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    transform-style: preserve-3d;
}

Vivimos en 2015 + y Flex Box es compatible con todos los principales navegadores modernos.

Será la forma en que se hacen los sitios web de aquí en adelante.

¡Apréndelo!

 101
Author: BAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-29 17:58:39

Todo el crédito va para el propietario de este enlace @Sebastian Ekström Link; por favor revise esto. Véalo en acción codepen . Al leer el artículo anterior también creé un violín demo.

Con solo tres líneas de CSS (excluyendo los prefijos de proveedor) podemos hacerlo con la ayuda de una transform: translateY centra verticalmente lo que queramos, incluso si no sabemos su altura.

La propiedad CSS transform se usa generalmente para rotar y escalar elementos, pero con su función translateY ahora podemos alinear verticalmente los elementos. Por lo general, esto debe hacerse con el posicionamiento absoluto o el establecimiento de alturas de línea, pero estos requieren que usted sepa la altura del elemento o solo funciona en texto de una sola línea, etc.

Entonces, para hacer esto escribimos:

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

Eso es todo lo que necesitas. Es una técnica similar al método de posición absoluta, pero con la ventaja de que no tenemos que establecer ninguna altura en el elemento o la propiedad position en el padre. Funciona directamente de la caja, incluso en Internet Explorer 9!

Para hacerlo aún más simple, podemos escribirlo como un mixin con sus prefijos de proveedor.

 52
Author: ankitd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-19 22:40:11

Las Flexboxes que se introdujeron en CSS3 son la solución:

section {
    display: flex;
    display: -webkit-flex;
    height: 200px;
    width: 50%;
    margin: auto;
    border-radius: 20px;
    border: 5px solid black;
    background-color: yellow;
}

p {
    text-align: center;
    margin: auto; /* Important */
    font-family: Calibri;
}
<section>
    <p>
        I'm center!<br/>
        Flexboxes are great!
    </p>
</section>

Nota : Reemplace la línea anterior que marcó como importante con una de estas líneas, si desea centrar el texto:

1) Solo verticalmente:

margin: auto 0;

2) Solo horizontalmente:

margin: 0 auto;

ACTUALIZAR: Como he notado, este truco funciona con cuadrículas (display: grid), también.

 30
Author: MAChitgarha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-30 12:11:35

Enfoque flexible

div {
  width: 250px;
  min-height: 50px;
  line-height: 50px;
  text-align: center;
  border: 1px solid #123456;
  margin-bottom:5px;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
<div>
  <span>Lorem ipsum dolor sit amet.</span>
</div>
<div>
 16
Author: Jürg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-29 16:13:53

La solución aceptada como respuesta es perfecta para usar line-height lo mismo que la altura de div, pero esta solución no funciona perfectamente cuando el texto está envuelto O está en dos líneas.

Pruebe este si el texto está envuelto o está en varias líneas dentro de un div.

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

Para más referencia, ver:

 15
Author: Pranav Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-11 16:34:34

Intenta esta solución :

.EXTENDER {
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    height: 100%;
    overflow-y: hidden;
    overflow-x: hidden;
}

.PADDER-CENTER {
    width: 100%;
    height: 100%;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: center;
    -moz-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    -webkit-box-align: center;
    -moz-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
}
<div class="EXTENDER">
  <div class="PADDER-CENTER">
    <div contentEditable="true">Edit this text...</div>
  </div>
</div>

Construido usando CSS+.

 11
Author: Marconi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-29 17:52:32

También puede usar las siguientes propiedades.

display: flex; 
align-content: center; 
justify-content : center;
 9
Author: satwik boorgula,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-15 13:01:33

Puede utilizar el siguiente fragmento de código como referencia. Está funcionando como un encanto para mí:

<!DOCTYPE html>
    <html lang="de">
        <head>
            <title>Vertically Center Text</title>
            <style>
                html, body {
                    height: 100%;
                    margin: 0;
                    padding: 0;
                    width: 100%;
                }
                body {
                    display: table;
                }
                .centered-text {
                    text-align: center;
                    display: table-cell;
                    vertical-align: middle;
                }
            </style>
        </head>

        <body style="background:#3cedd5">
            <div class="centered-text">
                <h1>Yes, it's my landing page</h1>
                <h2>Under construction, coming soon!!!</h2>
            </div>
        </body>
    </html>

La salida del fragmento de código anterior es la siguiente:

Introduzca la descripción de la imagen aquí

Crédito del código fuente: ¿Cómo puedo centrar verticalmente el texto con CSS? - Código Puran

 9
Author: Akshay Pethani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-19 18:02:50

Otra manera:

No establezca el atributo height del div, sino use padding: para lograr el efecto. De manera similar a line-height, solo funciona si tiene una línea de texto. Aunque de esta manera, si tiene más contenido, el texto seguirá centrado, pero el div en sí será un poco más grande.

Así que en lugar de ir con:

div {
  height:120px;
  line-height: 120px;
}

Puedes decir:

div {
   padding: 60px 0; //Maybe 60 minus font-size divided by two, if you want to be  exact
}

Esto establecerá la parte superior e inferior padding de la div a 60px, y la izquierda y la derecha padding a cero, haciendo que el div 120px (más la altura de su fuente) sea alto, y colocando el texto verticalmente centrado en el div.

 8
Author: Eseirt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-17 16:40:08

Para todas sus necesidades de alineación vertical!

Declare este Mixin:

@mixin vertical-align($position: relative) {
  position: $position;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

Luego inclúyelo en tu elemento:

.element{
    @include vertical-align();
}
 5
Author: Gothburz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-27 17:04:20

No estoy seguro de que alguien haya tomado la ruta writing-mode, pero creo que resuelve el problema limpiamente y tiene un amplio apoyo :

.vertical {
  //border: 1px solid green;
  writing-mode: vertical-lr;
  text-align: center;
  height: 100%;
  width: 100%;
}
.horizontal {
  //border: 1px solid blue;
  display: inline-block;
  writing-mode: horizontal-tb;
  width: 100%;
  text-align: center;
}
.content {
  text-align: left;
  display: inline-block;
  border: 1px solid #e0e0e0;
  padding: .5em 1em;
  border-radius: 1em;
}
<div class="vertical">
  <div class="horizontal">
    <div class="content">
      I'm centered in the vertical and horizontal thing
    </div>
  </div>
</div>

Esto, por supuesto, funcionará con cualquier dimensión que necesite (además del 100% del padre). Si descomentas las líneas fronterizas, te será útil familiarizarte.

JSFiddle demo para que violines.

Soporte Caniuse: 85.22% + 6.26% = 91.48% (incluso IE está en!)

 4
Author: Carles Alcolea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-27 23:27:30

Aún mejor idea para esto. Usted puede hacer así también

body,
html {
  height: 100%;
}

.parent {
  white-space: nowrap;
  height: 100%;
  text-align: center;
}

.parent:after {
  display: inline-block;
  vertical-align: middle;
  height: 100%;
  content: '';
}

.centered {
  display: inline-block;
  vertical-align: middle;
  white-space: normal;
}
<div class="parent">
  <div class="centered">
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
</div>
 4
Author: Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-24 11:01:02

Para una sola línea de texto (o un solo carácter) puede utilizar esta técnica:

Se puede usar cuando #box tiene una altura relativa no fija, en %.

<div id="box"></div>

#box::before {
    display: block;
    content: "";
    height: 50%;
}

#box::after {
    vertical-align: top;
    line-height: 0;
    content: "TextContent";
}

Ver demostración en vivo en JsBin (más fácil de editar CSS) o JsFiddle (más fácil de cambiar la altura del marco de resultado).

Si desea colocar el texto interno en HTML, no en CSS, entonces necesita ajustar el contenido del texto en un elemento adicional inline y editar #box::after para que coincida. (Y, por supuesto, content: propiedad debe ser eliminado.)
Por ejemplo,
<div id="box"><span>TextContent</span></div>
En este caso, #box::after debe sustituirse por #box span.

Para el soporte IE8 debe reemplazar :: con :.

 3
Author: user,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-01 21:10:08

La forma simple y versátil es (como el enfoque de la tabla michielvoo):

[ctrv]{
    display:table !important;
}

[ctrv] > *{ /* adressing direct discendents */
      display:table-cell;
      vertical-align: middle;
      // text-align: center; /* optional */
}

Usar este atributo (o una clase equivalente) en una etiqueta padre funciona incluso para que muchos niños se alineen:

<parent ctrv>  <ch1/>  <ch2/>   </parent>
 3
Author: bortunac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-19 22:37:01

Pruebe la propiedad transform:

 #box {
  height: 90px;
  width: 270px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
 <div Id="box">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
 3
Author: sstauross,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-27 13:46:05

Una solución muy simple y más potente para alinear verticalmente el centro:

.outer-div {
  height: 200px;
  width: 200px;
  text-align: center;
  border: 1px solid #000;
}

.inner {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  color: red;
}
<div class="outer-div">
  <span class="inner">No data available</span>
</div>
 3
Author: Manish Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-27 09:33:58

El siguiente código pondrá el div en el medio de la pantalla independientemente del tamaño de la pantalla o div tamaño:

.center-screen {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  min-height: 100vh;
}
 <html>
 <head>
 </head>
 <body>
 <div class="center-screen">
 I'm in the center
 </div>
 </body>
 </html>

Ver más detalles acerca de flex aquí.

 3
Author: Caner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-02 10:21:56

Vi las respuestas anteriores, y funcionarán solo para ese ancho de pantalla (no sensible). Para el responsivo tienes que usar flex.

Ejemplo:

div{ display:flex; align-item:center;}
 3
Author: Saravana priyan S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-19 18:00:32

Intente el siguiente código:

display: table-cell;
vertical-align: middle;

div {
  height: 80%;
  width: 100%;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
  background: #4CAF50;
  color: #fff;
  font-size: 50px;
  font-style: italic;
}
<div>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>
 3
Author: Rafiqul Islam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-19 18:01:18

Me gustaría extender la respuesta de @michielvoo para liberar la necesidad de altura de línea y la respiración de altura div. Es básicamente una versión simplificada como esta:

div {
  width: 250px;
  /* height: 100px;
  line-height: 100px; */
  text-align: center;
  border: 1px solid #123456;
  background-color: #bbbbff;
  padding: 10px;
  margin: 10px;
}

span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>All grown-ups were once children... but only few of them remember it</span>
</div>

<div>
  <span>And now here is my secret, a very simple secret: It is only with the heart that one can see rightly; what is essential is invisible to the eye.</span>
</div>

NOTA: la parte comentada de css es necesaria para fixed-height de encerrar div.

 2
Author: mPrinC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-16 10:23:38

Necesitaba una fila de elefantes clicables, centrados verticalmente, pero sin usar una tabla para sortear algunas rarezas de Internet Explorer 9.

Finalmente encontré el CSS más bonito (para mis necesidades) y es genial con Firefox, Chrome e Internet Explorer 11. Tristemente Internet Explorer 9 todavía se está riendo de mí...

div {
  border: 1px dotted blue;
  display: inline;
  line-height: 100px;
  height: 100px;
}

span {
  border: 1px solid red;
  display: inline-block;
  line-height: normal;
  vertical-align: middle;
}

.out {
  border: 3px solid silver;
  display: inline-block;
}
<div class="out" onclick="alert(1)">
  <div> <span><img src="http://www.birdfolk.co.uk/littleredsolo.png"/></span> </div>
  <div> <span>A lovely clickable option.</span> </div>
</div>

<div class="out" onclick="alert(2)">
  <div> <span><img src="http://www.birdfolk.co.uk/bang2/Ship01.png"/></span> </div>
  <div> <span>Something charming to click on.</span> </div>
</div>

Obviamente no necesitas las fronteras, pero pueden ayudarte a ver cómo funciona.

 1
Author: Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-23 19:02:44

Póngalo dentro de button en lugar de div si no le importa su pequeño efecto visual 3D.

#box
{
  height: 120px;
  width: 300px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
}
<button Id="box" disabled>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</button>
 1
Author: URL87,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-19 18:09:48
.element{position: relative;top: 50%;transform: translateY(-50%);}

Agregue este pequeño código en la propiedad CSS de su elemento. Es impresionante. ¡Inténtalo!

 0
Author: Rahul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-19 22:43:18

Los navegadores más nuevos ahora soportan la función CSS calc. Si usted está apuntando a estos navegadores es posible que desee mirar en hacer algo como esto:

<div style="position: relative; width: 400px; height: 400px; background-color: red">
  <span style="position: absolute; line-height: 40px; height: 80px; text-align: center; width: 300px; overflow: hidden; top: calc(50% - 40px); left: calc(50% - 150px);">
    Here are two lines that will be centered even if the parent div changes size.
  </span>
</div>

La clave es usar style = "top: calc(50% - [innerFixedHeightInPX/2]px); height: [innerFixedHeightInPX]px;" dentro de un div padre absoluto o relativamente posicionado.

 0
Author: bruceceng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-29 16:01:44

Donde quiera que el estilo de centro vertical significa que puede probar display:table-cell y vertical-align:middle.

Ejemplo:

#box
{
  display: table-cell;
  vertical-align: middle;
  height: 90px;
  width: 270px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  margin-top: 20px;
  margin-left: 5px;
}
<div Id="box">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
 0
Author: Ayyappan K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-21 11:19:19

.box {  
  width: 100%;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}

.height {
  line-height: 170px;
  height: 170px;
}

.transform { 
  height: 170px;
  position: relative;
}

.transform p {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
<h4>Using Height</h4>
<div class="box height">
  Lorem ipsum dolor sit
</div>

<hr />

<h4>Using Transform</h4>
<div class="box transform">
  <p>Lorem ipsum dolor sit</p>
</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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-22 15:03:18

Posicionamiento absoluto y Estiramiento

Al igual que con el método anterior, este comienza estableciendo el posicionamiento en los elementos padre e hijo como relativo y absoluto respectivamente. A partir de ahí las cosas difieren.

En el código a continuación, una vez más he utilizado este método para centrar el hijo tanto horizontal como verticalmente, aunque puede usar el método solo para centrar vertical.

Html

<div id="parent">
    <div id="child">Content here</div>
</div>

Css

#parent {position: relative;}
#child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 50%;
    height: 30%;
    margin: auto;
}

La idea con esto el método consiste en intentar que el elemento hijo se extienda a los 4 bordes estableciendo los valores superior, inferior, derecho e izquierdo en 0. Debido a que nuestro elemento hijo es más pequeño que nuestros elementos padre, no puede alcanzar los 4 bordes.

Establecer auto como el margen en los 4 lados sin embargo hace que los márgenes opuestos sean iguales y muestra nuestro div hijo en el centro del div padre.

Desafortunadamente lo anterior no funcionará en IE7 y por debajo y al igual que el método anterior, el contenido dentro del div hijo puede crecer demasiado grande haciendo que se oculte.

 0
Author: ArifMustafa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-03 15:34:01