Centrando verticalmente un div dentro de otro div


Quiero centrar un div que se agrega dentro de otro div.

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

Este es el CSS que estoy usando actualmente.

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

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

Como puede ver,el enfoque que uso ahora depende de los valores de ancho y alto de innerDiv.Si el ancho/alto cambia, tendré que modificar margin-top y margin-left values.Is ¿hay alguna solución genérica que pueda usar para centrar el innerDiv siempre independientemente de su tamaño?

Me di cuenta de que el uso de margin:auto puede alinear horizontalmente el innerDiv a la medio.¿Pero qué hay de la alineación vertical media?

Author: Khánh, 2011-06-27

23 answers

Tl;dr

Vertical align middle funciona, pero tendrá que usar table-cell en su elemento padre y inline-block en el elemento hijo.

Esta solución no va a funcionar en IE6 & 7.
El tuyo es el camino más seguro para ir para ellos.
Pero ya que etiquetaste tu pregunta con CSS3 y HTML5 estaba pensando que no te importa usar una solución moderna.

La solución clásica (diseño de tabla)

Esta fue mi respuesta original. Todavía funciona bien y es la solución con el más amplio soporte. El diseño de tabla afectará su rendimiento de renderizado, por lo que sugeriría que use una de las soluciones más modernas.

He aquí un ejemplo


Probado en:

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

HTML

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

CSS

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

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

Solución Moderna (transform)

Dado que las transformaciones son bastante bien soportadas ahora hay una manera más fácil de hacerlo.

CSS

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

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

Demo


♥ mi solución moderna favorita (flexbox)

Comencé a usar flexbox cada vez más también está bien soportado ahora Es, con mucho, la forma más fácil.

CSS

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

Demo

Más ejemplos y posibilidades: Comparar todos los métodos en una página

 628
Author: meo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-27 15:50:16

Otra forma de lograr este centrado horizontal y vertical es:

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

(Referencia )

 106
Author: user700284,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-19 00:24:00

Otra forma es usar Transform Translate

El Div exterior debe establecer su position a relative o fixed, y el Div Interior debe establecer su position a absolute, top y left a 50% y aplicar un transform: translate(-50%, -50%).

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

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

Probado en:

  • Opera 24.0 (mínimo 12.1)
  • Safari 5.1.7 (mínimo 4 con el prefijo-webkit -)
  • Firefox 31.0 (mínimo 3.6 con prefijo-moz, de 16 sin prefijo)
  • Chrome 36 (mínimo 11 con el prefijo-webkit -, de 36 sin prefijo)
  • IE 11, 10 (mínimo 9 con prefijo-ms -, de 10 sin prefijo)
  • ¿Puedo Usar Más navegadores?
 41
Author: Emanuel Ve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-01 21:17:32

Vertical Alinear Cualquier cosa con solo 3 líneas de CSS

HTML

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

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

</div>

Más simple

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

CSS

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

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

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

De acuerdo con shouldiprefix estos son los únicos prefijos que necesita

También puede usar % como el valor de la propiedad' height ' de .padre-de-elemento, siempre y cuando el padre del elemento tenga altura o algún contenido que expanda su tamaño vertical.

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

En lugar de atarme en un nudo con CSS difícil de escribir y difícil de mantener (¡eso también necesita una cuidadosa validación entre navegadores!) Me parece mucho mejor renunciar a CSS y utilizar en lugar maravillosamente simple HTML 1.0:

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

Esto logra todo lo que el póster original quería, y es robusto y mantenible.

 16
Author: Iron Pillow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-12 02:59:15

Personalmente prefiero el truco de usar un pseudo elemento oculto para abarcar toda la altura del contenedor exterior, y alinearlo verticalmente con el otro contenido. Chris Coyier tiene un buen artículo sobre la técnica. http://css-tricks.com/centering-in-the-unknown / La gran ventaja de esto es la escalabilidad. No tienes que saber la altura del contenido o preocuparte de que crezca/se reduzca. Esta solución escala :).

Aquí hay un violín con todo el CSS que necesitará y un ejemplo de trabajo. http://jsfiddle.net/m5sLze0d /

.center:before {
    content: ""; /* Adding Extra Space Above Element */
    display: inline-block;
    height: 100%;
    margin-right: -0.3em;
    vertical-align: middle;
}
.center_element {
    display:inline-block;
    float:none;
    vertical-align:middle;
    white-space:normal;
    text-align:left;
}
 5
Author: Harry Robbins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-22 16:31:11

Cuando su height no está configurado (automático); puede darle a la división interna un poco de relleno (superior e inferior) para que se centre verticalmente:

<div>
    <div style="padding-top:20px;padding-bottom:20px">
    <!--content-->
    </div>
</div>
 3
Author: Majid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-01 09:07:17

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

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

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

Puede hacerlo simplemente agregando el estilo CSS mencionado anteriormente. Todo lo mejor. para la consulta escribir comentario

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

Centrando verticalmente elementos div dentro de otro div

Simplemente establezca el contenedor en display:table y luego los elementos internos en display:table-cell. Establezca un height en el contenedor, y luego establezca vertical-align:middle en los elementos internos. Esto tiene una amplia compatibilidad hasta los días de IE9.

Solo tenga en cuenta que la alineación vertical dependerá de la altura del contenedor padre.

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

.inner
{
display:table-cell;
vertical-align:middle;
color:#FFF;
padding-left:10px;
padding-right:10px;
}
<div class="cn">
  <div class="inner">Item 1</div>
  <div class="inner">Item 2</div>
</div>
 3
Author: Volomike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-10 04:43:18

He estado usando la siguiente solución desde hace más de un año, funciona con IE 7 y 8 también.

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

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

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

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

<div class="outer">
    <div class="emptyDiv verticalCenter"></div>
    <div class="inner verticalCenter">
        <p>Line 1</p>
        <p>Line 2</p>
    </div>
</div>
 2
Author: Arsh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-27 19:55:58

Esto funciona para mí. Se pueden definir la anchura y la altura del div exterior.

Aquí el código:

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

.outer > div:first-child {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  background: red;
}
<div class="outer">
  <div class="inner">
    Put here your text or div content!
  </div>
</div>
 2
Author: phlegx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-24 21:54:22

Enlace de violín http://jsfiddle.net/dGHFV/2515/>

Prueba esto

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

    #innerDiv{
        width: 284px;
        height: 290px;
        position:absolute;
        top: 0px;
        left:0px;
        right:0px;
        bottom:0px;
        margin:auto;
        border:1px solid green;
    }
 2
Author: Friend,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 09:49:27

Si usted todavía no entendió después de leer las maravillosas respuestas dadas anteriormente.

Aquí hay dos ejemplos simples de cómo puedes lograrlo.

Usando la pantalla: table-cell

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

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

Usando flex-box (pantalla: flex)

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

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

Nota: Compruebe la compatibilidad del navegador de display: table-cell y flex antes de usar las implementaciones mencionadas anteriormente.

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

Introduzca la descripción de la imagen aquí 100% funciona

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

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

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

 2
Author: Mangesh Jadhav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-17 06:48:24

Para innerdiv que no especifica su valor de altura,no hay una solución css pura para hacerlo centrado verticalmente.una solución javascript podría ser obtener el offsetHeight de innerdiv, luego calcular el estilo.marginTop.

 1
Author: james li,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-27 08:30:26

Puede hacer esto con un simple bloque javascript (jQuery).

CSS :

#outerDiv{
    height:100%;
}

Javascript:

<script type="text/javascript">
    $(document).ready(function () {
        $("#innerDiv").css('top', ($(window).height() - $("#content").height()) / 2);
    });
</script>
 1
Author: Ghanesh MV,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-22 18:51:05

Intenta alinear el elemento interno de esta manera:

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

Y por supuesto:

position: absolute;
 1
Author: VonAxt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-21 12:42:52

Puede centrar el div vertical y horizontalmente en CSS usando flex;

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

    }

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

}

Y el segundo es el siguiente;

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

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

Y el HTML resultante:

    <div id="outerDiv">
        <div id="innerDiv"></div>
    </div>
 1
Author: Tariq Javed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-28 21:44:08

Esto funcionará camino de vuelta a IE6!

<!DOCTYPE html> se requiere en IE6 también! [forzará el modo estricto predeterminado de IE6 también ].

(por supuesto, la coloración de la caja es solo para fines de demostración )

    #outer{
        width: 205px;
        height: 205px;
        margin: auto; 
        text-align: center;
    }
    #inner{
        text-align: left;
        vertical-align: middle;
        width: 120px;
        height: 120px;
        display: inline-block;
   
    }
    #center{
        height: 100%; width:0px;
        vertical-align: middle;
        display: inline-block;
    }
    div {background: rgba(0,128,255,.6)}
<div id=outer>
    <div id=center></div><div id=inner> The inner DIV
    </div>
</div>
 1
Author: Bekim Bacaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-15 08:32:51

Text align-center on parent element, display inline-block on child element. Esto va a centrar todo lo más cualquier cosa. Creo que se llama "bloque flotante".

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

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

Esta también es una buena alternativa para float, buena suerte!

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

Centrando verticalmente un div dentro de otro div

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

#innerDiv{
  width: 284px;
  height: 290px;
  
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%); /* IE 9 */
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */	
  
  background-color: grey;
}
<div id="outerDiv">
  <div id="innerDiv"></div>
</div>
 0
Author: antelove,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-25 07:09:35

Para alinear el centro tanto vertical como horizontalmente:

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

#child {
     display:table-cell;
     vertical-align:middle;
}
 0
Author: Bhimashankar Sutar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-28 13:32:38

Sé que esa pregunta fue creada hace un año... De todos modos gracias CSS3 usted puede fácilmente alinea verticalmente div en div (ejemplo allí http://jsfiddle.net/mcSfe/98/)

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

div
{
display:-moz-box;
-moz-box-align:center;
} 
 -6
Author: godlark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-06 22:46:29