Cómo alinear a al centro (horizontalmente / ancho) de la página [duplicar]


Author: Sunil Garg, 2009-06-05

27 answers

<body>
    <div style="width:800px; margin:0 auto;">
        centered content
    </div>
</body>
 969
Author: AgileJon,
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-03-07 16:48:20

position: absolute y luego top:50% y left:50% coloca el borde superior en el centro vertical de la pantalla, y el borde izquierdo en el centro horizontal, luego agregando margin-top a negativo de altura del div i.e-100 lo desplaza por encima de 100, de manera similar para margin-left. Esto consigue div exactamente en el centro de la página.

#outPopUp {
  position: absolute;
  width: 300px;
  height: 200px;
  z-index: 15;
  top: 50%;
  left: 50%;
  margin: -100px 0 0 -150px;
  background: red;
}
<div id="outPopUp"></div>  
 285
Author: Summo,
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-18 14:11:27

Moderno Flexbox la solución es el camino a seguir en / a partir de 2015. justify-content: center se utiliza para que el elemento padre alinee el contenido con el centro del mismo.

HTML

<div class="container">
  <div class="center">Center</div>
</div>

CSS

.container {
  display: flex;
  justify-content: center;
}
.center {
  width: 800px;
}

Salida

.container {
  display: flex;
  justify-content: center;
}
.center {
  width: 800px;
  background: #5F85DB;
  color: #fff;
  font-weight: bold;
  font-family: Tahoma;
}
<div class="container">
  <div class="center">Centered div with left aligned text.</div>
</div>
 56
Author: Manoj 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-07-01 21:49:30
  1. ¿Quieres decir que quieres centrarlo vertical u horizontalmente? Usted dijo que especificó el height a 800px, y quería que el div no se estirara cuando el width era mayor que eso...

  2. Para centrar horizontalmente, puede usar el atributo margin: auto; en css. Además, tendrás que asegurarte de que los elementos body y html no tengan ningún margen o relleno:

html, body { margin: 0; padding: 0; }
#centeredDiv { margin-right: auto; margin-left: auto; width: 800px; }
 55
Author: Tomas Lycken,
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-09 19:15:29

Para que también funcione correctamente en Internet Explorer 6 tienes que hacerlo de la siguiente manera:

HTML

<body>
    <div class="centered">
        centered content
    </div>
</body>

CSS

body {
    margin: 0;
    padding: 0;
    text-align: center; /* !!! */
}

.centered {
    margin: 0 auto;
    text-align: left;
    width: 800px;
}
 36
Author: Kevin Dungs,
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-08-20 19:23:55
<div></div>
div {
  display: table;
  margin-right: auto;
  margin-left: auto;
}
 31
Author: Mohammad,
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 12:15:48

También puedes usarlo así:

<div style="width: 60%; margin: 0px auto;">
    Your contents here...
</div>
 25
Author: RajeshKdev,
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-29 22:41:23

Simplemente use la etiqueta central justo después de la etiqueta del cuerpo, y la etiqueta central final justo antes de que termine el cuerpo

<body>
<center>
........your code here.....
</center>
</body>

Esto funcionó para mí con todos los navegadores que he probado

 14
Author: Bharat Chhatre,
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-05-11 11:44:51

Agregue esta clase al div que desea centrado (que debe tener un ancho establecido):

.marginAutoLR
{
    margin-right:auto;
    margin-left:auto;
}

O, agregue el material de margen a su clase div, así:

.divClass
{
    width:300px;
    margin-right:auto;
    margin-left:auto;
}
 12
Author: Taylor Brown,
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-31 13:36:07

Esto se puede lograr fácilmente a través de flex container.

.container{
 width: 100%;
 display: flex;
 height: 100vh;
 justify-content: center;
}

.item{
 align-self: center;
}

Enlace de vista previa

 11
Author: Roy,
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-28 18:17:16

Use la propiedad css flex: http://jsfiddle.net/cytr/j7SEa/6/show /

body {                       /* centerized */
  display: box;
  flex-align: center;
  flex-pack: center;
}
 10
Author: ,
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-12-28 15:45:05

Algunas otras configuraciones preexistentes de código anterior que evitarán que div page centering L & R sean: 1) otras clases ocultas en enlaces externos de hojas de estilo. 2) otras clases incrustadas en algo como un img (como para los controles de formato de impresión CSS externos más antiguos). 3) el código de leyenda con ID y / o CLASES entrará en conflicto con una clase div con nombre.

 6
Author: Dennis Struck,
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-05-16 17:20:32

Centrado sin especificar el ancho del div:

body {
  text-align: center;
}

body * {
  text-align: initial;
}

body div {
  display: inline-block;
}

Esto es algo así como <center> lo hace la etiqueta, excepto:

  • todos los elementos childs en línea directa (por ejemplo. <h1>) de <center> también se posicionará para centrar
  • el elemento de bloque en línea puede tener un tamaño diferente (configuración comapred a display:block) de acuerdo con los valores predeterminados del navegador
 5
Author: Igor Ivancha,
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 11:53:02
body, html{
    display:table;
    height:100%;
    width:100%;
}
.container{
    display:table-cell;
    vertical-align:middle;
}
.container .box{
    width:100px;
    height:100px;
    background:red;
    margin:0 auto;

}

Http://jsfiddle.net/NPV2E /

"width:100%" para la etiqueta "body" es solo por ejemplo. En el proyecto real puede eliminar esta propiedad.

 4
Author: Andrei Gordiichuk,
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-11-19 16:09:45

Si tiene algún contenido regular y no solo una línea de texto, la única razón posible que conozco es calcular el margen.
He aquí un ejemplo:

HTML

<div id="supercontainer">
  <div id="middlecontainer">
    <div class="common" id="first">first</div>
    <div id="container">
      <div class="common" id="second">second</div>
      <div class="common" id="third">third</div>
    </div>
  </div>
</div>

CSS

body {
  margin: 0;
  padding: 0;
}

.common {
  border: 1px solid black;
}

#supercontainer {
  width: 1200px;
  background: aqua;
  float: left;
}

#middlecontainer {
  float: left;
  width: 104px;
  margin: 0 549px;
}

#container {
  float: left;
}

#first {
  background: red;
  height: 102px;
  width: 50px;
  float: left;
}

#second {
  background: green;
  height: 50px;
  width: 50px;
}

#third {
  background: yellow;
  height: 50px;
  width: 50px;
}

Entonces, #supercontainer es tu "whole page" y es width es 1200px.
#middlecontainer es div con el contenido de su sitio; es width 102px. En caso de que se conozca el width de contenido, debe dividir el tamaño de la página en 2, y subestructura del resultado de la mitad del contenido width:
1200 / 2 - (102 / 2) = 549;

Sí, también veo que esto es DER GROSSE fail de CSS.

 4
Author: rodnower,
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 11:46:34

Use justify-content y align-items para alinear horizontal y verticalmente a div

Https://developer.mozilla.org/de/docs/Web/CSS/justify-content https://developer.mozilla.org/en/docs/Web/CSS/align-items

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>
 4
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:30:08

Esto funciona en IE también, los márgenes automáticos no.

.centered {
    position:           absolute;
    display:            inline-block;
    left:           -500px;
    width:          1000px;
    margin:             0 50%;
}
 3
Author: Glen,
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-04-09 20:02:04

Div centrado vertical y horizontalmente dentro del padre sin fijar el tamaño del contenido

Mira este ejemplo (haz clic). Muy simple, y funciona para alturas flexibles también. Perfecto si no tienes contenido con altura fija.

Y aquí (haga clic) es una buena visión general con algunas otras soluciones.

Y aquí (clic) otro ejemplo con una solución de ancho flexible con el famoso truco del -50%

 3
Author: Wilt,
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:25

Simple http://jsfiddle.net/8pd4qx5r /

html {
  display: table;
  height: 100%;
  width: 100%;
}

body {
  display: table-cell;
  vertical-align: middle;
}

.content {
  margin: 0 auto;
  width: 260px;
  text-align: center;
  background: pink;
}
 3
Author: Igor Ivancha,
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 11:47:39

Utilice el siguiente código para centrar la caja div:

.box-content{
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    position: absolute;
    width: 800px;
    height: 100px;
    background-color: green;
}
<div class="box-content">
</div>
 3
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-03-29 22:50:53
.middle {
   margin: auto;
   text-align: center;
}
 1
Author: KBH,
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-06-18 17:51:30

Si el contenido del centro está dentro de otros divs, solo el margen puede salvarlo. Nada más. Lo enfrento siempre cuando no uso framework como Bootstrap.

 1
Author: Nurul Akter Towhid,
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-25 22:07:25
<body>
    <div style=" display: table; margin: 250 auto;">
        In center
    </div>
</body>

Si desea cambiar la posición vertical, cambie el valor de 250 y puede organizar el contenido según su necesidad. No hay necesidad de dar el ancho y otros parámetros.

 1
Author: Aashutosh Shrivastava,
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-29 22:49:37

En mi caso, el tamaño de la pantalla del teléfono es desconocido, esto es lo que hice.

HTML

<div class="loadingImg"></div>

CSS

.loadingImg{
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 9999999;
    border:0;
    background: url('../images/loading.gif') no-repeat center;
    background-size: 50px 50px;
    display: block;
    margin: 0 auto;
    -webkit-border-radius: 50px;
    border-radius: 50px;
}

JS (antes de que necesite mostrar este DIV)

$(".loadingImg").css("height",$(document).height());     
$(".loadingImg").css("width",$(document).width());     
$(".loadingImg").show(); 
 1
Author: Edye Chan,
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-10-21 04:02:15
<parent>
 <child>
 </child>
</parent>

Padre { posición: relativa } niño { posición: absoluta, izquierda: 50%, transformar: translateX(-50%) }

 1
Author: Levon,
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-17 21:12:28

Una pregunta bastante antigua con muchas respuestas, pero por alguna razón ninguna de ellas funcionó para mí realmente. Esto es lo que funcionó para mí y funciona en todo el navegador también:

.center {
    text-align: center;
    height: 100%;
    /* Safari, Opera, and Chrome */
    display:-webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;
    /* Firefox */
    display:-moz-box;
    -moz-box-pack:center;
    -moz-box-align:center;
    /* Internet Explorer 10 */
    display:-ms-flexbox;
    -ms-flex-pack:center;
    -ms-flex-align:center;
}
 0
Author: Osei-Bonsu Christian,
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-29 08:13:23

Obtener el ancho de la pantalla que hacer margen a la izquierda 25% hacer margen a la derecha 25% de esta manera el contenido de su contenedor se sentará en el medio . ejemplo: supongamos que el ancho del contenedor = 800px;

div class='container' width='device-width' id='updatedContent'> 
<p id='myContent'></p
<contents></contents>
<contents></contents>
</div>
if($("#myContent").parent===$("updatedContent"))
{
$("#myContent").css({
'left':'-(device-width/0.25)px';
'right':'-(device-width/0.225)px';
});
}
 0
Author: mark dibe,
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 19:55:26