Cómo centrar el div verticalmente dentro del div padre absolutamente posicionado
Estoy tratando de conseguir contenedor azul en el medio de uno rosa, sin embargo parece vertical-align: middle;
no hace el trabajo en ese caso.
<div style="display: block; position: absolute; left: 50px; top: 50px;">
<div style="text-align: left; position: absolute;height: 56px;vertical-align: middle;background-color: pink;">
<div style="background-color: lightblue;">test</div>
</div>
</div>
Resultado:
Expectativa:
Por favor sugiera cómo puedo lograr eso.
8 answers
En primer lugar, tenga en cuenta que vertical-align
solo es aplicable a celdas de tabla y elementos de nivel inline.
Hay un par de maneras de lograr alineaciones verticales que pueden o no satisfacer sus necesidades. Sin embargo te mostraré dos métodos de mis favoritos:
1. Usando transform
y top
.valign {
position: relative;
top: 50%;
transform: translateY(-50%);
/* vendor prefixes omitted due to brevity */
}
<div style="position: absolute; left: 50px; top: 50px;">
<div style="text-align: left; position: absolute;height: 56px;background-color: pink;">
<div class="valign" style="background-color: lightblue;">test</div>
</div>
</div>
El punto clave es que un valor porcentual en top
es relativo al height
del bloque que contiene; mientras que un valor porcentual en transform
s es relativo al tamaño de la caja en sí (la caja delimitadora).
Si experimenta problemas de renderización de fuentes (fuente borrosa), la solución es agregar perspective(1px)
a la declaración transform
para que se convierta en:
transform: perspective(1px) translateY(-50%);
Vale la pena señalar que CSS transform
es compatible con IE9 + .
2. Usando inline-block
(pseudo-)elementos
En este método, tenemos dos elementos hermanos inline-block
que están alineados verticalmente en el centro por la declaración vertical-align: middle
.
Uno de ellos tiene un height
de 100%
de su padre y el otro es nuestro elemento deseado cuyo queríamos alinearlo en el medio.
.parent {
text-align: left;
position: absolute;
height: 56px;
background-color: pink;
white-space: nowrap;
font-size: 0; /* remove the gap between inline level elements */
}
.dummy-child { height: 100%; }
.valign {
font-size: 16px; /* re-set the font-size */
}
.dummy-child, .valign {
display: inline-block;
vertical-align: middle;
}
<div style="position: absolute; left: 50px; top: 50px;">
<div class="parent">
<div class="dummy-child"></div>
<div class="valign" style="background-color: lightblue;">test</div>
</div>
</div>
Finalmente, debemos usar uno de los métodos disponibles para eliminar la brecha entre los elementos de nivel inline.
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-04 23:55:36
Usa esto:
.Absolute-Center {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
Consulte este enlace: https://www.smashingmagazine.com/2013/08/absolute-horizontal-vertical-centering-css/
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-25 10:53:59
Utilice flex blox en su div posicionado absoutely para centrar su contenido.
Ver ejemplo https://plnkr.co/edit/wJIX2NpbNhO34X68ZyoY?p=preview
.some-absolute-div {
display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -moz-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
-moz-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
-moz-align-items: center;
align-items: center;
}
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-05 21:55:00
Centrar vertical y horizontalmente:
.parent{
height: 100%;
position: absolute;
width: 100%;
top: 0;
left: 0;
}
.c{
position: absolute;
top: 50%;
left: 0;
right: 0;
transform: translateY(-50%);
}
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-14 15:39:53
Puede usar display:table
/table-cell;
.a{
position: absolute;
left: 50px;
top: 50px;
display:table;
}
.b{
text-align: left;
display:table-cell;
height: 56px;
vertical-align: middle;
background-color: pink;
}
.c {
background-color: lightblue;
}
<div class="a">
<div class="b">
<div class="c" >test</div>
</div>
</div>
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-11 13:10:58
Por favor, compruebe esta respuesta a un problema similar.
Esta es, con mucho, la forma más fácil que he encontrado.
Https://stackoverflow.com/a/26079837/4593442
NOTA. Usé display: -webkit-flex; en lugar de display: flex; para probar dentro de safari.
NOTA AL PIE. Soy un novato solamente, compartiendo la ayuda de alguien que es claramente experimentado.
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 12:18:29
Aquí es una forma sencilla de usar Top object.
Eg: Si el tamaño absoluto del elemento es 60px.
.absolute-element {
position:absolute;
height:60px;
top: calc(50% - 60px);
}
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-20 07:46:01
Una solución simple adicional
HTML:
<div id="d1">
<div id="d2">
Text
</div>
</div>
CSS:
#d1{
position:absolute;
top:100px;left:100px;
}
#d2{
border:1px solid black;
height:50px; width:50px;
display:table-cell;
vertical-align:middle;
text-align:center;
}
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-25 09:46:15