¿Cómo se centra fácilmente horizontalmente un uso de CSS? [duplicar]


 636
Author: cmcginty, 2009-03-06

22 answers

En el caso de un div de ancho no fijo (es decir, no sabes cuánto espacio ocupará el div).

#wrapper {
  background-color: green; /* for visualization purposes */
  text-align: center;
}
#yourdiv {
  background-color: red; /* for visualization purposes */
  display: inline-block;
}
<div id="wrapper">    
    <div id="yourdiv">Your text</div>
</div>

Tenga en cuenta que el ancho de #yourdiv es dinámico -> crecerá y se reducirá para acomodar el texto dentro de él.

Puede comprobar la compatibilidad del navegador en Caniuse

 687
Author: Tivie,
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-29 00:24:07

En la mayoría de los navegadores esto funcionará:

div.centre {
  width: 200px;
  display: block;
  background-color: #eee;
  margin-left: auto;
  margin-right: auto;
}
<div class="centre">Some Text</div>

En IE6 tendrá que añadir otro exterior div:

div.layout {
  text-align: center;
}

div.centre {
  text-align: left;
  width: 200px;
  background-color: #eee;
  display: block;
  margin-left: auto;
  margin-right: auto;
}
<div class="layout">
  <div class="centre">Some Text</div>
</div>
 542
Author: Antony Scott,
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-02 22:12:45
margin: 0 auto;

Como ck ha dicho, min-width no es compatible con todos los navegadores

 51
Author: Russ Cam,
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:10:45

El título de la pregunta y el contenido son realmente diferentes, así que publicaré dos soluciones para eso usando Flexbox.

Supongo que Flexbox reemplazará / agregará a la solución estándar actual en el momento en que IE8 e IE9 se destruyan completamente;)

Compruebe la corriente Tabla de compatibilidad de navegadores para flexbox

Elemento único

.container {
  display: flex;
  justify-content: center;
}
<div class="container">
  <img src="http://placehold.it/100x100">
</div>

Múltiples elementos pero centrando solo uno

Predeterminado el comportamiento es flex-direction: row que alineará todos los elementos secundarios en una sola línea. Ajustarlo a flex-direction: column ayudará a que las líneas se apilen.

.container {
  display: flex;
  flex-direction: column;
}
.centered {
  align-self: center;
}
<div class="container">
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   </p>
  <div class="centered"><img src="http://placehold.it/100x100"></div>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>
</div>
 32
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
2015-08-14 10:29:01

CSS, HTML:

div.mydiv {width: 200px; margin: 0 auto}
<div class="mydiv">
    
    I am in the middle
    
</div>

Su diagrama también muestra un elemento de nivel de bloque (que normalmente es un div), no uno en línea.

De la parte superior de mi cabeza, min-width es compatible con FF2+/Safari3+/IE7+. Se puede hacer para IE6 usando hackety CSS, o un simple poco de JS.

 25
Author: sjh,
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-07 10:36:10
.center {
   margin-left: auto;
   margin-right: auto;
}

El ancho mínimo no está soportado globalmente, pero se puede implementar usando

.divclass {
   min-width: 200px;
}

Entonces puede configurar su div para ser

<div class="center divclass">stuff in here</div>
 22
Author: cjk,
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-04 17:10:01

Si los navegadores antiguos no son un problema, utilice HTML5 / CSS3. Si lo son, aplique polyfills y siga utilizando HTML5 / CSS3. Asumo que su div no tiene márgenes o rellenos aquí, pero son relativamente fáciles de tener en cuenta. El código sigue.

.centered {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}

Lo que esto hace es:

  1. Coloque el div en relación con su contenedor;
  2. Coloque el límite izquierdo de div al 50% de su ancho de contenedor horizontalmente;
  3. Traducir horizontalmente en un 50% de el ancho propio div .

Es fácil imaginar este proceso para confirmar que el div se centraría horizontalmente eventualmente. Como bono, puedes centrar verticalmente sin costo adicional:

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

La ventaja de este enfoque es que no tiene que hacer ninguna cosa contraintuitiva, como considerar su div como un texto, envolverlo en un contenedor adicional (a menudo semánticamente inútil) o darle un ancho fijo, que no siempre es posible.

No olvide los prefijos de proveedor para transform si es necesario.

 22
Author: wh1t3cat1k,
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-02 12:53:24

Debe usar position: relative y text-align: center en el elemento padre y luego display: inline-block en el elemento hijo que desea centrar. Este es un patrón de diseño CSS simple que funcionará en todos los navegadores principales. Aquí hay un ejemplo a continuación o echa un vistazo al ejemplo de CodePen .

p {
  text-align: left;
}
.container {
  position: relative;
  display: block;
  text-align: center;
}
/* Style your object */

.object {
  padding: 10px;
  color: #ffffff;
  background-color: #556270;
}
.centerthis {
  display: inline-block;
}
<div class="container">

  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p>

  <span class="object centerthis">Something Centered</span>

  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p>
</div>
 7
Author: Joshua Pekera,
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-13 20:59:44

Puedes usar margin: 0 auto en tu css en lugar de margin-left: auto; margin-right: auto;

 6
Author: Zawarudo,
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-09-04 10:50:18

Por favor, utilice el siguiente código su div estará en el centro

.class-name{
display:block;
margin:0 auto;

}

 4
Author: RiyazAhmed,
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-21 09:45:28

Después de nueve años pensé que era hora de traer una nueva versión. Aquí están mis dos (y ahora uno) favoritos.

Margen

Establezca margin en auto. Usted debe saber que la secuencia de dirección es margin: *top* *right* *bottom* *left*; o margin: *top&bottom* *left&right*

aside{
    display: block;
    width: 50px;
    height: 100px;
    background-color: green;
    float: left;
}

article{
    height: 100px;
    margin: 0 0 0 50px; /* 50px aside width */
    background-color: grey;
}

div{
  margin: 0 auto;
  display:block;
  width: 60px;
  height: 60px;
  background-color: blue;
  color: white;
}
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <aside>
        </aside>
        <article>           
                <div>The div</div>
        </article>
    </body>
</html>

¡Depricated, no uses esto!

Use las etiquetas <center></center> como una envoltura alrededor de su <div></div>.

Ejemplo:

aside{
    display:block;
    background-color:green;
    width: 50px;
    height: 100px;
    float: left;
}

center{
    display:block;
    background-color:grey;
    height: 100px;
    margin-left: 50px; /* Width of the aside */
}

div{
    display:block; 
    width: 60px; 
    height: 60px; 
    background-color:blue;
    color: white;
}
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <aside>
        </aside>
        <article>
            <center>
                <div>The div</div>
            </center>
        </article>
    </body>
</html>
 3
Author: Orry Vandermeulen,
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 02:17:14

Aquí añado la respuesta adecuada

Puede usar este fragmento de código y personalizarlo. Aquí utilizo el bloque de niños 2.Esto debería mostrar el centro de la página. Puede utilizar uno o varios bloques.

<html>
<head>
<style>
#parent {
    width: 100%;
    border: solid 1px #aaa;
    text-align: center;
    font-size: 20px;
    letter-spacing: 35px;
    white-space: nowrap;
    line-height: 12px;
    overflow: hidden;
}

.child {
    width: 100px;
    height: 100px;
    border: solid 1px #ccc;
    display: inline-block;
    vertical-align: middle;
}
</style>
</head>

<body>

<div class="mydiv" id="parent">


<div class="child">
Block 1
</div>
<div class="child">
Block 2
</div>

</div>
</body>
</html>
 2
Author: CodeSnippet,
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-07 19:12:03

.center {
  height: 20px;
  background-color: blue;
}

.center>div {
  margin: auto;
  background-color: green;
  width: 200px;
}
<div class="center">
  <div>You text</div>
</div>

JsFiddle

 2
Author: Lex,
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-29 08:07:23

Si conoce el ancho de su div y está fijo, puede usar el siguiente css:

margin-left: calc(50% - 'half-of-your-div-width');

Donde 'la mitad del ancho de tu div' debería ser (obviamente) la mitad del ancho de tu div.

 2
Author: P.Petkov,
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-01 12:40:08

Si su <div> tiene position: absolute usted necesita usar width: 100%;

#parent {
    width: 100%;
    text-align: center;
}

    #child {
        display: inline-block;
    }
 1
Author: Marcio Mazzucato,
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-24 20:36:58

En tu archivo html escribes:

<div class="banner">
  Center content
</div>

El archivo css que escribes:

.banner {
display: block;
margin: auto;
width: 100px;
height: 50px;
}

Funciona para mí.

 1
Author: krekto,
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-23 14:56:27

El uso de margin-left:auto y margin-right:auto puede no funcionar en ciertas situaciones. Aquí hay una solución que siempre funcionará. Usted especifica un ancho requerido y luego establece un margen izquierdo a la mitad del ancho restante.

    <div style="width:80%; margin-left:calc(10%);">
        your_html
    </div>
 1
Author: azakgaim,
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-07 15:40:29

Agregue esta clase a su archivo css, funcionará perfectamente pasos a seguir:

1) crea esto primero

<div class="center-role-form">
  <!--your div (contrent) place here-->
</div>

2) añade esto a tu css

.center-role-form {
    width: fit-content;
    text-align: center;
    margin: 1em auto;
}
 1
Author: Urvashi Bhatt,
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-29 11:46:38

La mejor respuesta a esta pregunta es usar margin-auto pero para usarlo debe conocer el width de su div en px o %.

Código CSS:

div{
    width:30%;
    margin-left:auto;
    margin-right:auto;
}
 0
Author: Ayman EL Ouafi,
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-15 17:31:12

Utilizo etiquetas div y span junto con propiedades css como block, cross-browser inline-block y text-align center, vea mi ejemplo simple

<!DOCTYPE html>
<html>
    <head>
       <title>Page Title</title>
       <style>
           .block{display:block;}
           .text-center{text-align:center;}
           .border-dashed-black{border:1px dashed black;}
           .inline-block{
                 display: -moz-inline-stack;
                 display: inline-block;
                 zoom: 1;
                 *display: inline;
            }
           .border-solid-black{border:1px solid black;}
           .text-left{text-align:left;}
        </style>
    </head>
    <body>
          <div class="block text-center border-dashed-black">
              <span class="block text-center">
                  <span class="block"> 
        <!-- The Div we want to center set any width as long as it is not more than the container-->
                      <div class="inline-block text-left border-solid-black" style="width:450px !important;">
                             jjjjjk
                      </div> 
                  </span>
              </span>
          </div>
      </body>
   </html>
 0
Author: amachree tamunoemi,
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-20 02:28:55

Puede usar la posición: relativa; y luego establecer los valores izquierdo y superior:

.cenverDiv{
    position:relative;
    left:30%;
    top:0px;
}
 -3
Author: goli55,
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-14 11:47:02

Usando jQuery:

$(document).ready(function() {
    $(".myElement").wrap( '<span class="myElement_container_new"></span>' ); // for IE6
    $(".myElement_container_new").css({// for IE6
        "display" : "block",
        "position" : "relative",
        "margin" : "0",
        "padding" : "0",
        "border" : "none",
        "background-color" : "transparent",
        "clear" : "both",
        "text-align" : "center"
    });
    $(".myElement").css({
        "display" : "block",
        "position" : "relative",
        "max-width" : "75%", // for example
        "margin-left" : "auto",
        "margin-right" : "auto",
        "clear" : "both",
        "text-align" : "left"
    });
});

O, si desea centrar cada elemento con clase".myElement":

$(document).ready(function() {
    $(".myElement").each(function() {
        $(this).wrap( '<span class="myElement_container_new"></span>' ); // for IE6
        $(".myElement_container_new").css({// for IE6
            "display" : "block",
            "position" : "relative",
            "margin" : "0",
            "padding" : "0",
            "border" : "none",
            "background-color" : "transparent",
            "clear" : "both",
            "text-align" : "center"
        });
        $(this).css({
            "display" : "block",
            "position" : "relative",
            "max-width" : "75%",
            "margin-left" : "auto",
            "margin-right" : "auto",
            "clear" : "both",
            "text-align" : "left"
        });
    });
});
 -3
Author: Riccardo Volpe,
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-28 23:59:07