Cómo centrar div absoluto horizontalmente usando CSS?


Tengo un div y quiero que esté centrado horizontalmente, aunque lo estoy dando margin:0 auto; no está centrado...

.container {
    position: absolute;
    top: 15px;
    z-index: 2;
    width:40%;
    max-width: 960px;
    min-width: 600px;
    height: 60px;
    overflow: hidden;
    background: #fff; 
    margin:0 auto;
}
Author: lorem monkey, 2013-07-31

8 answers

Necesitas establecer left:0; right:0;.

Esto especifica hasta qué punto se deben desplazar los bordes del margen desde los lados de la ventana.

Http://www.w3.org/TR/CSS2/visuren.html#position-props


Http://jsfiddle.net/SS6DK /

CSS

.container
{
  position: absolute;
  top: 15px;
  z-index: 2;
  width:40%;
  max-width: 960px;
  min-width: 600px;
  height: 60px;
  overflow: hidden;
  background: #fff;
  margin: 0 auto;
  left: 0;
  right: 0;
}

Nota: Debes definir el widtho esta respuesta no funcionará. Esto significa que esta respuesta no es útil para elementos con anchuras dinámicas.

 359
Author: thgaskell,
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-14 10:49:50

Esto no funciona en IE8, pero podría ser una opción a considerar. Es especialmente útil si no desea especificar un ancho.

.element
{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
 107
Author: Adel,
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-13 04:02:49

Aunque las respuestas anteriores son correctas, pero para que sea simple para los novatos, todo lo que necesita hacer es establecer el margen, izquierda y derecha. el siguiente código lo hará siempre que width se establezca y position sea absoluta:

margin: 0 auto;
left: 0;
right: 0;

Demo:

.centeredBox {
    margin: 0 auto;
    left: 0;
    right: 0;
   
   
   /** Position should be absolute */
    position: absolute;
    /** And box must have a width, any width */
    width: 40%;
    background: #faebd7;
   
   }
<div class="centeredBox">Centered Box</div>
 12
Author: Meta Pakistani,
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-27 03:53:46

Flexbox? Puedes usar flexbox.

.box {
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  
  -webkit-justify-content: center;
  justify-content: center;

}

.box div {
  border:1px solid grey;
  flex: 0 1 auto;
  align-self: auto;
  background: grey;
}
<div class="box">
  <div class="A">I'm horizontally centered.</div>
</div>
 5
Author: Ron Royston,
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-16 02:39:27
.centerDiv {
    position: absolute;
    left: 0;
    right: 0;
    margin: 0 auto;
    text-align:center;
}
 2
Author: Z. Rahman Raju,
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-16 01:44:02

Tan fácil, solo use las propiedades margin y left, right:

.elements {
 position: absolute;
 margin-left: auto;
 margin-right: auto;
 left: 0;
 right: 0;
}

Puedes ver más en este consejo = > Cómo configurar el elemento div para que se centre en html-Obinb blog

 2
Author: Neko,
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-26 14:47:04

Aquí hay un enlace por favor use esto para hacer el div en el centro si la posición es absoluta.

HTML:

<div class="bar"></div>

CSS:

.bar{
  width:200px;
  border-top:4px solid red;
  position:absolute;
  margin-left:auto;
  margin-right:auto;
  left:0;
  right:0;
}

Ejemplo jsfiddle

 0
Author: Amit 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-31 18:39:17

No puedes usar margin:auto; en elementos position:absolute;, simplemente elimínalo si no lo necesitas, sin embargo, si lo haces, podrías usar left:30%; ((100%-40%)/2) y media queries para los valores max y min:

.container {
    position: absolute;
    top: 15px;
    left: 30%;
    z-index: 2;
    width:40%;
    height: 60px;
    overflow: hidden;
    background: #fff;
}

@media all and (min-width:960px) {

    .container {
        left: 50%;
        margin-left:-480px;
        width: 960px;
    }

}

@media all and (max-width:600px) {

    .container {
        left: 50%;
        margin-left:-300px;
        width: 600px;
    }

}
 -1
Author: Leonard Pauli,
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-07-31 17:39:46