¿Cómo centrar un elemento horizontal y verticalmente?


Estoy tratando de centrar el contenido de mis pestañas verticalmente, pero cuando agrego el estilo css display:inline-flex, la alineación horizontal de texto desaparece.

¿Cómo puedo hacer ambas alineaciones de texto x e y para cada una de mis pestañas?

* { box-sizing:border-box; }
#leftFrame {
  background-color:green;
  position:absolute;
  left:0;
  right:60%;
  top:0;
  bottom:0;
}
#leftFrame #tabs {
  background-color:red;
  position:absolute;
  top:0;
  left:0;
  right:0;
  height:25%;
}
#leftFrame #tabs div {
  border:2px solid black;
  position:static;
  float:left;
  width:50%;
  height:100%;
  text-align:center;
  display: inline-flex;
  align-items: center;
}
<div id=leftFrame>
  <div id=tabs>
    <div>first</div>
    <div>second</div>        
  </div>
</div>
 256
Author: shuji, 2013-10-19

13 answers

  • Enfoque 1 - transform translateX/translateY:

    Ejemplo Aquí / Completo Ejemplo De La Pantalla

    En los navegadores compatibles (la mayoría de ellos), puede utilizar top: 50%/left: 50% en combinación con translateX(-50%) translateY(-50%) para centrar dinámicamente vertical/horizontalmente el elemento.

.container {
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
<div class="container">
    <span>I'm vertically/horizontally centered!</span>
</div>

  • Enfoque 2 - método Flexbox:

    Ejemplo Aquí / Completo Ejemplo de Pantalla

    En los navegadores compatibles , establezca display del elemento objetivo en flex y use align-items: center para el centrado vertical y justify-content: center para el centrado horizontal. Simplemente no olvide agregar prefijos de proveedor para soporte adicional del navegador ( ver ejemplo).

html, body, .container {
    height: 100%;
}

.container {
    display: -webkit-flexbox;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
    justify-content: center;
}
<div class="container"> 
  <span>I'm vertically/horizontally centered!</span>
</div>

  • Enfoque 3 - table-cell/vertical-align: middle:

    Ejemplo Aquí / Pantalla Completa Ejemplo

    En algunos casos, tendrá que asegurarse de que el html/body la altura del elemento se establece en 100%.

    Para la alineación vertical, establezca el width/height a 100% y añádase display: table. Luego, para el elemento hijo, cambie display a table-cell y agregue vertical-align: middle.

    Para el centrado horizontal, puede agregar text-align: center para centrar el texto y cualquier otro elemento secundario inline. Alternativamente, puede usar margin: 0 auto, asumiendo que el elemento es block nivel.

html, body {
    height: 100%;
}
.parent {
    width: 100%;
    height: 100%;
    display: table;
    text-align: center;
}
.parent > .child {
    display: table-cell;
    vertical-align: middle;
}
<section class="parent">
    <div class="child">I'm vertically/horizontally centered!</div>
</section>

  • Enfoque 4 - Absolutamente posicionado 50% desde la parte superior con desplazamiento:

    Ejemplo Aquí / Completo Ejemplo De La Pantalla

    Este enfoque asume que el texto tiene una altura conocida, en este caso, 18px. Simplemente coloque absolutamente el elemento 50% desde la parte superior, en relación con el elemento padre. Utilice un valor negativo margin-top que sea la mitad del altura conocida del elemento, en este caso - -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;
}
<div class="container">
    <p>I'm vertically/horizontally centered!</p>
</div>

  • Enfoque 5-El método line-height (Menos flexible - no sugerido):

    Ejemplo Aquí

    En algunos casos, el elemento padre tendrá una altura fija. Para el centrado vertical, todo lo que tiene que hacer es establecer un valor line-height en el elemento hijo igual a la altura fija del elemento padre.

    Aunque esta solución funcionará en en algunos casos, vale la pena señalar que no funcionará cuando hay varias líneas de texto - como este.

.parent {
    height: 200px;
    width: 400px;
    background: lightgray;
    text-align: center;
}

.parent > .child {
    line-height: 200px;
}
<div class="parent">
    <span class="child">I'm vertically/horizontally centered!</span>
</div>
 476
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-04 09:53:06

Si CSS3 es una opción (o tiene una alternativa) puede usar transform:

.center {
    right: 50%;
    bottom: 50%;
    transform: translate(50%,50%);
    position: absolute;
}

A diferencia del primer enfoque anterior, no desea usar left:50% con la traducción negativa porque hay un error de desbordamiento en IE9+. Utilice un valor positivo correcto y no verá barras de desplazamiento horizontales.

 14
Author: Mr Bullets,
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-04 19:25:16

La mejor manera de centrar una caja tanto vertical como horizontalmente, es usar dos contenedores:

El contenedor externo:

  • debe tener display: table;

El contenedor interior:

  • debe tener display: table-cell;
  • debe tener vertical-align: middle;
  • debe tener text-align: center;

El cuadro de contenido:

  • debe tener display: inline-block;
  • debe ajustar la alineación horizontal del texto, a menos que desee que el texto sea centrado

Demo:

body {
    margin : 0;
}

.outer-container {
    display: table;
    width: 80%;
    height: 120px;
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Center this!
     </div>
   </div>
</div>

Ver también este Violín!

Centrado en el centro de la página:

Para centrar su contenido en el centro de su página, agregue lo siguiente a su contenedor externo:

  • position : absolute;
  • width: 100%;
  • height: 100%;

Aquí hay una demostración para eso:

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%;
    height: 100%;
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Center this!
     </div>
   </div>
</div>

Véase también esto Fiddle!

 6
Author: John Slegers,
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-15 12:52:41

La solución más simple y limpia para mí es usar la propiedad CSS3 "transform":

.container {
  position: relative;
}

.container a {
  position: absolute;
  top: 50%;
  transform: translate(0,-50%);
}
<div class="container">
  <a href="#">Hello world!</a>
</div>
 3
Author: tocqueville,
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-03 21:52:42

Para centrar el Div en una página compruebe el enlace del violín

#vh {
    border-radius: 15px;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);
    padding: 25px;
    width: 200px;
    height: 200px;
    background: white;
    text-align: center;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}
<div id="vh">Div to be aligned vertically</div>

Update Otra opción es utilizar flex box compruebe el enlace del violín

.vh {
    background-color: #ddd;
    height: 200px;
    align-items: center;
    display: flex;
}
.vh > div {
    width: 100%;
    text-align: center;
    vertical-align: middle;
}
<div class="vh">
    <div>Div to be aligned vertically</div>
</div>
 2
Author: Moes,
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-04 23:06:23

Otro enfoque es utilizar la tabla:

<div style="border:2px solid #8AC007; height:200px; width:200px;">
  <table style="width:100%; height:100%">
    <tr style="height:100%">
      <td style="height:100%; text-align:center">hello, multiple lines here, this is super long, and that is awesome, dude</td>
    </tr>
  </table>
</div>
 2
Author: iamcoming,
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-03 21:52:46

    .align {
        display: flex;
        width: 400px;
        height: 400px;
        border: solid 1px black;
        align-items: center;
        justify-content: space-around;
    }
    .align div:first-child {
        width: 20px;
        height: 20px;
        background-color: red;
        position: absolute; 
    }
    .align div {
        width: 20px;
        height: 20px;
        background-color: blue;
    }
    <div class='align'>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>

El primer hijo estará alineado vertical y horizontalmente en el centro

 2
Author: Krishna,
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-07-21 14:19:05
  • Enfoque 6

/*Change units to "%", "px" or whatever*/

#wrapper{
  width: 50%;
  height: 70vh;
  background: rgba(0,0,0,.5);
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}
#left{
  width: 50%;
  height: 50vh;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  background: red;
}
#right{
  width: 50%;
  height: 50vh;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  background: green;
}
.txt{
  text-align: center;
  line-height: 50vh;
}
<div id="wrapper">
   <div id="left" class="txt">Left</div>
   <div id="right" class="txt">Right</div>
</div>
    .container{ 
               width: 50%;  //Your container width here
               height: 50%; //Your container height here
               position: absolute; 
               top: 0; 
               right: 0;  
               bottom: 0; 
               left: 0; 
               margin: auto;
    }
 1
Author: derp,
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-02 12:52:14

A continuación se muestra el enfoque de caja flexible para obtener el resultado deseado

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Flex-box approach</title>
<style>
  .tabs{
    display: -webkit-flex;
    display: flex;
    width: 500px;
    height: 250px;
    background-color: grey;
    margin: 0 auto;
    
  }
  .f{
    width: 200px;
    height: 200px;
    margin: 20px;
    background-color: yellow;
    margin: 0 auto;
    display: inline; /*for vertically aligning */
    top: 9%;         /*for vertically aligning */
    position: relative; /*for vertically aligning */
  }
</style>
</head>
<body>

    <div class="tabs">
        <div class="f">first</div>
        <div class="f">second</div>        
    </div>

</body>
</html>
 1
Author: Manish62,
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 13:46:27

Ejecute este fragmento de código y vea un div alineado vertical y horizontalmente.

html,
body,
.container {
  height: 100%;
  width: 100%;
}
.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
.mydiv {
  width: 80px;
}
<div class="container">
  <div class="mydiv">h & v aligned</div>
</div>
 1
Author: JFathi,
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-03 18:35:29

Para centrar vertical y horizontalmente un elemento también podemos usar las propiedades mencionadas a continuación.

Esta propiedad CSS aligns-items verticalmente y acepta los siguientes valores:

Flex-start: Los elementos se alinean con la parte superior del contenedor.

Flex-end: Los elementos se alinean con la parte inferior del contenedor.

Center: Los elementos se alinean en el centro vertical del contenedor.

Baseline: Items display at the baseline del contenedor.

Estirar : Los artículos se estiran para que quepan en el recipiente.

Esta propiedad CSS justify-content , que alinea los elementos horizontalmente y acepta los siguientes valores:

Flex-start: Los elementos se alinean al lado izquierdo del contenedor.

Flex-end: Los elementos se alinean al lado derecho del contenedor.

Center: Los elementos se alinean en el centro del contenedor.

Espacio-entre : Visualización de elementos con el mismo espacio entre ellos.

Space-around: Los elementos se muestran con el mismo espacio alrededor de ellos.

 1
Author: Divyanshu Rawat,
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-02-21 08:53:38

Simplemente hacer arriba,abajo, izquierda y derecha a 0.

<html>
<head>
<style>
<div> 
{
position: absolute;
margin: auto;
background-color: lightblue;
width: 100px;
height :100px;
padding: 25px;
top :0;
right :0;
bottom:0;
left:0;
}


</style>
</head>
<body>

<div> I am in the middle</div>

</body>
</html>
 1
Author: yoginder bagga,
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-21 06:16:19

Enfoque css de cuadrícula

#wrapper {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);
}
.main {
    background-color: #444;
}
<div id="wrapper">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box main"></div>
</div>
 0
Author: Tomasz Zieliński,
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-02-11 19:22:46