Cómo alinear verticalmente una imagen dentro de un div?


Pregunta

¿Cómo se puede alinear una imagen dentro de un contenido div?

Ejemplo

En mi ejemplo, necesito centrar verticalmente el <img> en el <div> con class ="frame" :

<div class="frame" style="height: 25px;">
    <img src="http://jsfiddle.net/img/logo.png" />
</div>

.frame'la altura de s es fija y la altura de la imagen es desconocida. Puedo agregar nuevos elementos en .frame si esa es la única solución. Estoy tratando de hacer esto en IE≥7, Webkit, Gecko.

Ver el jsfiddle aquí

.frame {
    height: 25px;      /* equals max image height */
    line-height: 25px;
    width: 160px;
    border: 1px solid red;
    
    text-align: center; margin: 1em 0;
}
img {
    background: #3A6F9A;
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}
        
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=250 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=25 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=23 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=21 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=19 />
</div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=17 />
</div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=15 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=13 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=11 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=9 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=7 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=5 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=3 />
 </div>
Author: Nitin Bisht, 2011-09-01

30 answers

La única (y la mejor forma de cross-browser) que conozco es usar un ayudante inline-block con height: 100% y vertical-align: middle en ambos elementos.

Así que hay una solución: http://jsfiddle.net/kizu/4RPFa/4570 /

.frame {
    height: 25px;      /* equals max image height */
    width: 160px;
    border: 1px solid red;
    white-space: nowrap; /* this is required unless you put the helper span closely near the img */
    
    text-align: center; margin: 1em 0;
}

.helper {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

img {
    background: #3A6F9A;
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=250px />
</div>
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=25px />
</div>
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=23px />
</div>
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=21px />
</div>
<div class="frame">
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=19px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=17px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=15px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=13px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=11px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=9px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=7px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=5px />
</div>
<div class="frame">
    <span class="helper"></span>
    <img src="http://jsfiddle.net/img/logo.png" height=3px />
</div>

O, si no desea tener un elemento adicional en los navegadores modernos y no le importa usar expresiones IE, puede usar un pseudo-elemento y agregarlo a IE usando una expresión conveniente, que se ejecuta solo una vez por elemento, por lo que no habrá ninguna cuestiones de rendimiento:

La solución con :before y expression() para IE: http://jsfiddle.net/kizu/4RPFa/4571/

.frame {
    height: 25px;      /* equals max image height */
    width: 160px;
    border: 1px solid red;
    white-space: nowrap;
    
    text-align: center; margin: 1em 0;
}

.frame:before,
.frame_before {
    content: "";
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

img {
    background: #3A6F9A;
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}

/* Move this to conditional comments */
.frame {
    list-style:none;
    behavior: expression(
        function(t){
            t.insertAdjacentHTML('afterBegin','<span class="frame_before"></span>');
            t.runtimeStyle.behavior = 'none';
        }(this)
    );
}
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=250px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=25px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=23px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=21px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=19px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=17px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=15px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=13px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=11px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=9px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=7px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=5px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=3px /></div>

Cómo funciona:

  1. Cuando tienes dos inline-block elementos cerca uno del otro, puedes alinearlos uno al lado del otro, así que con vertical-align: middle obtendrás algo como esto:

    Dos bloques alineados

  2. Cuando usted tiene un bloque con altura fija (en px, em u otra unidad absoluta), puede establecer el altura de los bloques interiores en %.

  3. Entonces, agregar un inline-block con height: 100% en un bloque con altura fija alinearía otro elemento inline-block en él (<img/> en su caso) verticalmente cerca de él.
 1860
Author: kizu,
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-08-09 18:58:03

Esto podría ser útil:

div {
    position:relative;
    width:200px;
    height:200px;
}
img {
    position:absolute;
    top:0;
    bottom:0;
    margin:auto;
}
.image {
    min-height:50px
}

Referencia: http://www.student.oulu.fi / ~ laurirai / www / css / middle /

 453
Author: Tahir Yasin,
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-07-05 05:23:52

La solución de Matejkramny es un buen comienzo, pero las imágenes de gran tamaño tienen una relación incorrecta.
Aquí está mi tenedor:

Demo: https://jsbin.com/lidebapomi/edit?html, css, output

previo


HTML:
<div class="frame">
  <img src="foo"/>
</div>

CSS:

.frame {  
    height: 160px; /*can be anything*/
    width: 160px; /*can be anything*/
    position: relative;
}
img {  
    max-height: 100%;  
    max-width: 100%; 
    width: auto;
    height: auto;
    position: absolute;  
    top: 0;  
    bottom: 0;  
    left: 0;  
    right: 0;  
    margin: auto;
}
 394
Author: jomo,
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-17 11:14:30

Solución de 3 líneas:

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

Esto se aplica a cualquier cosa.

De aquí.

 167
Author: Jorge Orpinel,
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-19 03:00:10

Una solución CSS PURA:

Http://jsfiddle.net/3MVPM /

El CSS:

.frame {  
    margin: 1em 0;  
    height: 35px;
    width: 160px;
    border: 1px solid red;
    position: relative;
}  
img {  
    max-height: 25px;  
    max-width: 160px;  
    position: absolute;  
    top: 0;  
    bottom: 0;  
    left: 0;  
    right: 0;  
    margin: auto;  
    background: #3A6F9A;  
}

Cosas clave

// position: relative; - in .frame holds the absolute element within the frame
// top: 0; bottom: 0; left: 0; right: 0; - this is key for centering a component
// margin: auto; - centers the image horizontally & vertically
 127
Author: code ninja,
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
2011-09-05 13:36:26

De esta manera puede centrar una imagen verticalmente (demo):

div{
  height:150px; //IE7fix
  line-height: 150px;
}
img{
  vertical-align: middle;
  margin-bottom:0.25em;
}
 95
Author: Zoli Szabó,
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-18 13:39:13

Para aquellos que aterrizaron en este post y están interesados en una solución más moderna, y que no tienen necesidad de soportar navegadores heredados, puede hacer esto:

.frame {
    display: flex;
    /*Uncomment below to center horizontally*/
    /*justify-content: center;*/
    align-items: center;
}

img {
    height: auto;
}

/* Styling stuff not needed for demo */
.frame {
    max-width: 900px;
    height: 200px;
    margin: auto;
    background: #222;
}
p {
    max-width: 900px;
    margin: 20px auto 0;
}
img {
    width: 150px;
}
<div class="frame">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9988/hand-pointing.png">
</div>

Aquí hay un bolígrafo: http://codepen.io/ricardozea/pen/aa0ee8e6021087b6e2460664a0fa3f3e

 95
Author: Ricardo Zea,
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-03-20 16:56:08

Puede intentar establecer el CSS de PI en display: table-cell; vertical-align: middle;

 19
Author: Yeodave,
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
2011-09-07 16:31:30

Hay una solución súper fácil con flexbox!

.frame {
    display: flex;
    align-items: center;
}
 14
Author: BBlackwo,
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-21 00:56:41

Solución de imagen de fondo Eliminé el elemento de imagen todos juntos y lo establecí como fondo del div con una clase de .frame

Http://jsfiddle.net/URVKa/2 /

Esto al menos funciona bien en IE8, FF6 y Chrome13

He comprobado, esta solución no funcionará para reducir las imágenes más grandes que la altura 25px. Hay una propiedad llamada background-size que establece el tamaño del elemento, pero es CSS3 que entraría en conflicto con el requisito IE7.

Me gustaría le aconsejamos que rehaga las prioridades de su navegador y diseñe los mejores navegadores disponibles, u obtenga algún código de servidor para cambiar el tamaño de las imágenes si desea usar esta solución

 12
Author: Benjamin Udink ten Cate,
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-10-17 18:41:15

Puede intentar debajo del código

.frame{
 display:flex;
 justify-content: center;
 align-items: center;
 width:100%;
} 
<div class="frame" style="height: 25px;">
    <img src="http://jsfiddle.net/img/logo.png" />
</div>
 12
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-24 08:15:37

Usted podría hacer esto:

Demo

Http://jsfiddle.net/DZ8vW/1

CSS

.frame {
    height: 25px;      /* equals max image height */
    line-height: 25px;
    width: 160px;
    border: 1px solid red;

    text-align: center; margin: 1em 0;
    position: relative; /* Changes here... */
}
img {
    background: #3A6F9A;
    max-height: 25px;
    max-width: 160px;
    top: 50%;           /* here.. */
    left: 50%;           /* here... */
    position: absolute; /* and here */
}    


Javascript

$("img").each(function(){
    this.style.marginTop = $(this).height() / -2 + "px";
})
 11
Author: Joseph Marikle,
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-10-17 18:42:23

Http://jsfiddle.net/MBs64 /

.frame {
    height: 35px;      /* equals max image height */
    width: 160px;
    border: 1px solid red;
    text-align: center; 
    margin: 1em 0;
    display: table-cell;
    vertical-align: middle;
}
img {
    background: #3A6F9A;
    display: block;
    max-height: 35px;
    max-width: 160px;
}

La propiedad key es display: table-cell; for.marco. Div.frame se muestra como en línea con esto, por lo que debe envolverlo en un elemento de bloque.

Esto funciona en FF, Opera, Chrome, Safari e IE8+.

ACTUALIZAR

Para IE7 necesitamos agregar una expresión css:

*:first-child+html img {
    position: relative;
    top: expression((this.parentNode.clientHeight-this.clientHeight)/2+"px");
}
 10
Author: Webars,
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
2013-08-31 18:36:12

No estoy seguro de IE, pero bajo Firefox y Chrome, si tiene un img en un contenedor div, el siguiente css debería funcionar. Al menos para mí funciona bien:

div.img-container {
    display:table-cell;
    vertical-align: middle;
    height: 450px;
    width: 490px;
}

div.img-container img {
    max-height: 450px;
    max-width: 490px;
}
 6
Author: slava,
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-01-29 07:10:19

Pruebe esta solución con css puro http://jsfiddle.net/sandeep/4RPFa/72 / Puede ser el principal problema con su html. No use la cita cuando defina class & image height en tu html.

CSS:

.frame {
    height: 25px;      /* equals max image height */
    width: 160px;
    border: 1px solid red;
    position:relative;
    margin: 1em 0;
    top: 50%;
    text-align: center;
    line-height: 24px;
    margin-bottom:20px;
}

img {
    background: #3A6F9A;
    vertical-align: middle;
    line-height:0;
    margin:0 auto;
    max-height:25px;
}

EDITAR:

Cuando trabajo con la etiqueta img es dejar 3px to 2px espacio desde top. Ahora disminuyo line-height y es trabajo. css:

    .frame {
        height: 25px;      /* equals max image height */
        width: 160px;
        border: 1px solid red;
        margin: 1em 0;
        text-align: center;
        line-height:22px;
        *:first-child+html line-height:24px; /* for IE7 */
    }

    img {
        background: #3A6F9A;
        vertical-align: middle;
        line-height:0;    
        max-height:25px;
        max-width:160px;
    }
@media screen and (-webkit-min-device-pixel-ratio:0) {
    .frame {
        line-height:20px; /* webkit browsers */
    }

La propiedad line-height es render diferente en diferentes navegadores. Por lo tanto, tenemos que definir diferentes line-height navegadores de propiedades

Compruebe este ejemplo http://jsfiddle.net/sandeep/4be8t/11 /

Revisa este ejemplo acerca de line-height diferentes en diferentes navegadores diferencias de altura de entrada en Firefox y Chrome

 5
Author: sandeep,
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-23 10:31:35

Mi solución: http://jsfiddle.net/XNAj6/2/

<div class="container">
    <div class="frame">
        <img src="http://jsfiddle.net/img/logo.png" class="img" alt="" />
    </div>
</div>

.container {
    display: table;
    float: left;
    border: solid black 1px;
    margin: 2px;
    padding: 0;
    background-color: black;
    width: 150px;
    height: 150px;
}
.frame {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    border-width: 0;
}
.img {
    max-width: 150px;
    max-height: 150px;
    vertical-align: middle;
}
 5
Author: 0x100,
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
2013-08-23 05:57:45

Además, puede usar Flexbox para lograr el resultado correcto:

.parent {
  align-items: center; /* for vertical align */
  background: red;
  display: flex;
  height: 250px;
  /* justify-content: center; <- for horizontal align */
  width: 250px;
}
<div class="parent">
  <img class="child" src="https://cdn2.iconfinder.com/data/icons/social-icons-circular-black/512/stackoverflow-128.png" />
</div>
 5
Author: tourniquet,
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-08-24 13:09:43

Camino fácil que funciona para mí:

img {
    vertical-align: middle;
    display: inline-block;
    position: relative;
}

Funciona muy bien para Google Chrome. Pruebe este en otro navegador.

 4
Author: DOCTYPE HTML,
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-01-13 18:39:40

Esto funciona para los navegadores modernos (2016 en el momento de la edición) como se muestra en esta demostración en codepen

.frame {
    height: 25px;
    line-height: 25px;
    width: 160px;
    border: 1px solid #83A7D3;          
}
.frame img {
    background: #3A6F9A;
    display:inline-block;
    vertical-align: middle;
}

Es muy importante que dé a las imágenes una clase o use herencia para apuntar a las imágenes que necesita centradas. En este ejemplo usamos .frame img {} para que solo las imágenes envueltas por un div con una clase de .frame fueran objetivo.

 4
Author: anglimasS,
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-10-17 18:39:15

SOLUCIÓN USANDO LA TABLA Y LA CELDA DE LA TABLA

A veces se debe resolver mostrando como table/table-cell. Por ejemplo, una pantalla de título rápida. Es una forma recomendada por W3 también. Te recomiendo que revises este enlace llamado Centrando las cosas desde W3C.org

Los consejos utilizados aquí son:

  • Contenedor de posicionamiento absoluto mostrado como tabla
  • Alineado verticalmente al contenido central mostrado como cuadro-celda

.container {
position:absolute;
display:table;
width:100%;
height:100%;
}
.content {
display:table-cell;
vertical-align:middle;
}
<div class="container">
  <div class="content">
    <h1 style="text-align:center"> PEACE IN THE WORLD </h1>
 </div>
</div> 

Personalmente, en realidad no estoy de acuerdo sobre el uso de ayudantes para este propósito

 4
Author: Sam,
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-04-12 19:51:05

Si puede vivir con márgenes de tamaño de píxel, simplemente agregue font-size: 1px; a .frame. Pero recuerde, que ahora en el .frame 1em = 1px, lo que significa, es necesario establecer el margen en píxeles también.

Http://jsfiddle.net/feeela/4RPFa/96 /

EDITAR: ahora ya no está centrado en Opera {

 3
Author: feeela,
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
2011-09-07 16:49:53

Para centrar una imagen dentro de un contenedor (podría ser un logotipo) además de algún texto como este:

introduzca la descripción de la imagen aquí

Básicamente envolver la imagen

.outer-frame {
  border: 1px solid red;
  min-height: 200px;
  text-align: center; //only for align horizontally
}

.wrapper{
  line-height: 200px;
  border: 2px dashed blue;
  border-radius: 20px;
  margin: 50px
}

img {
//height: auto;
  vertical-align: middle;
}
<div class="outer-frame">
  <div class="wrapper">
    some text
    <img src="http://via.placeholder.com/150x150">
  </div>
</div>
 3
Author: juliangonzalez,
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-08-31 01:36:16

Yo tenía el mismo problema. Esto funciona para mí:

<style type="text/css">
div.parent {
     position: relative;
}

img.child {
    bottom: 0;
    left: 0;
    margin: auto;
    position: absolute;
    right: 0;
    top: 0;
}
</style>

<div class="parent">
    <img class="child">
</div>
 1
Author: algreat,
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
2013-01-26 19:46:52

Usando table y table-cell método hacer el trabajo, especialmente porque se dirige a algunos navegadores antiguos, así, creo un fragmento para usted que se puede ejecutar y comprobar el resultado:

.wrapper {
  position: relative;
  display: table;
  width: 300px;
  height: 200px;
}

.inside {
  vertical-align: middle;
  display: table-cell;
}
<div class="wrapper">
  <div class="inside">
    <p>Centre me please!!!</p>
  </div>
  <div class="inside">
    <img src="https://cdn2.iconfinder.com/data/icons/social-icons-circular-black/512/stackoverflow-128.png" />
  </div>
</div> 
 1
Author: Alireza,
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-06-28 13:51:25

Puedes usar esto:

.loaderimage {
position: absolute;
top: 50%;
left: 50%;
width: 60px;
height: 60px;
margin-top: -30px;/*50% of the height*/
margin-left: -30px;

}

 1
Author: Masoume Karvar,
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-09-19 12:52:17

La mejor solución es que

.block{
    /* decor */
    padding:0 20px;
    background:#666;
    border:2px solid #fff;
    text-align:center;
    /* important */
    min-height:220px;
    width:260px;
    white-space:nowrap;
}
.block:after{
    content:'';
    display:inline-block;
    height:220px; /* the same as min-height */
    width:1px;
    overflow:hidden;
    margin:0 0 0 -5px;
    vertical-align:middle;
}
.block span{
    vertical-align:middle;
    display:inline-block;
    white-space:normal;
}
 0
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
2015-02-03 06:16:33

He estado jugando con el uso de relleno para la alineación central. Tendrá que definir el tamaño del contenedor exterior de nivel superior, pero el contenedor interior debe cambiar de tamaño, y puede establecer el relleno en diferentes valores porcentuales.

Jsfiddle

<div class='container'>
  <img src='image.jpg' />
</div>

.container {
  padding: 20%;
  background-color: blue;
}

img {
  width: 100%;
}
 0
Author: steven iseki,
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-12-15 05:24:03

El viejo enlace JSFiddle que publiqué aquí ya no funcionó, esa es probablemente la razón de la votación negativa. Solo por el bien de que esta sea una respuesta válida todavía quiero publicar la solución jQuery de nuevo. Esto funciona para cada elemento que tiene la clase v_align aplicada a él. Estará centrado verticalmente en el padre y al redimensionar la ventana se volverá a calcular.

Enlace al JSFiddle

$(document).ready(function() {
  // define the class that vertial aligns stuff
  var objects = '.v_align';
  // initial setup
  verticalAlign(objects);

  // register resize event listener
  $(window).resize(function() {
    verticalAlign(objects);
  });
});

function verticalAlign(selector) {
  $(selector).each(function(val) {
    var parent_height = $(this).parent().height();
    var dif = parent_height - $(this).height()
    // should only work if the parent is larger than the element
    var margin_top = dif > 0 ? dif/2 : 0;
    $(this).css("margin-top", margin_top + "px");
  });
}
 0
Author: Chris,
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-07-19 09:17:33

¿Qué tal este?

position: absolute;
top: calc(50% - 0.5em);
left: calc(50% - 0.5em);
line-height: 1em;

Y puedes variar font-size

 0
Author: th3pirat3,
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-06-02 01:17:32

Desea alinear una imagen que tiene después de un texto / título y ambos están dentro de un div?

Ver en JSfiddle o Ejecutar Fragmento de código.

Solo asegúrese de tener un ID o una clase en todos sus elementos(div, img, title, etc.).

Para mí funciona esta solución en todos los navegadores(para dispositivos móviles debe adaptar su código con: @media).

h2.h2red {
color: red; 
font-size: 14px;
}
.mydivclass {
margin-top: 30px;
display: block;
}
img.mydesiredclass {
margin-right: 10px;  
display: block;  
float: left;/*If you want to allign the text with an image on the same row*/  
width: 100px;
heght: 100px;
margin-top: -40px/*Change this value to adapt to your page*/;
}
<div class="mydivclass">
<br />
<img class="mydesiredclass" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Wikipedia-logo-v2-en.svg/2000px-Wikipedia-logo-v2-en.svg.png">
<h2 class="h2red">Text alligned after image inside a div by negative manipulate the img postion</h2>
</div>
 0
Author: mariusfv,
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-06-08 07:01:33