Usar jQuery para centrar un DIV en la pantalla


¿Cómo puedo configurar un <div> en el centro de la pantalla usando jQuery?

Author: John Slegers, 2008-10-17

27 answers

Me gusta agregar funciones a jQuery para que esta función ayude:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
}

Ahora podemos escribir:

$(element).center();

Demo: Fiddle (con parámetro añadido)

 1049
Author: Tony L.,
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-01-26 11:04:54

Pongo un plugin de jquery aquí

VERSIÓN MUY CORTA

$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});

VERSIÓN CORTA

(function($){
    $.fn.extend({
        center: function () {
            return this.each(function() {
                var top = ($(window).height() - $(this).outerHeight()) / 2;
                var left = ($(window).width() - $(this).outerWidth()) / 2;
                $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
            });
        }
    }); 
})(jQuery);

Activado por este código :

$('#mainDiv').center();

VERSIÓN DEL PLUGIN

(function($){
     $.fn.extend({
          center: function (options) {
               var options =  $.extend({ // Default values
                    inside:window, // element, center into window
                    transition: 0, // millisecond, transition time
                    minX:0, // pixel, minimum left element value
                    minY:0, // pixel, minimum top element value
                    withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
                    vertical:true, // booleen, center vertical
                    horizontal:true // booleen, center horizontal
               }, options);
               return this.each(function() {
                    var props = {position:'absolute'};
                    if (options.vertical) {
                         var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                         if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                         top = (top > options.minY ? top : options.minY);
                         $.extend(props, {top: top+'px'});
                    }
                    if (options.horizontal) {
                          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                          left = (left > options.minX ? left : options.minX);
                          $.extend(props, {left: left+'px'});
                    }
                    if (options.transition > 0) $(this).animate(props, options.transition);
                    else $(this).css(props);
                    return $(this);
               });
          }
     });
})(jQuery);

Activado por este código :

$(document).ready(function(){
    $('#mainDiv').center();
    $(window).bind('resize', function() {
        $('#mainDiv').center({transition:300});
    });
);

¿Es eso correcto ?

ACTUALIZACIÓN:

De CSS-Trucos

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); /* Yep! */
  width: 48%;
  height: 59%;
}
 138
Author: molokoloco,
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-03 17:37:32

Recomendaría Utilidad de posición jQueryUI

$('your-selector').position({
    of: $(window)
});

Que te da muchas más posibilidades que solo centrar ...

 59
Author: cetnar,
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
2010-12-10 11:26:23

Aquí está mi ir en él. Terminé usándolo para mi clon Lightbox. La principal ventaja de esta solución es que el elemento permanecerá centrado automáticamente incluso si la ventana se redimensiona, lo que la hace ideal para este tipo de uso.

$.fn.center = function() {
    this.css({
        'position': 'fixed',
        'left': '50%',
        'top': '50%'
    });
    this.css({
        'margin-left': -this.outerWidth() / 2 + 'px',
        'margin-top': -this.outerHeight() / 2 + 'px'
    });

    return this;
}
 40
Author: Juho Vepsäläinen,
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-05-16 06:27:03

Puedes usar CSS solo para centrar así:

Ejemplo De Trabajo

.center{
    position: absolute;
    height: 50px;
    width: 50px;
    background:red;
    top:calc(50% - 50px/2); /* height divided by 2*/
    left:calc(50% - 50px/2); /* width divided by 2*/
}
<div class="center"></div>

calc() permite realizar cálculos básicos en css.

Documentación de MDN para calc()
Tabla de soporte del navegador

 25
Author: apaul,
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-10-31 15:26:42

Estoy expandiendo la gran respuesta dada por @TonyL. Estoy añadiendo matemáticas.abs () para envolver los valores, y también tengo en cuenta que jQuery podría estar en modo "sin conflicto", como por ejemplo en WordPress.

Recomiendo que envuelva los valores superior e izquierdo con Matemáticas.abs() como he hecho a continuación. Si la ventana es demasiado pequeña, y su diálogo modal tiene un cuadro de cierre en la parte superior, esto evitará el problema de no ver el cuadro de cierre. Función de Tony habría tenido potencialmente negativo valor. Un buen ejemplo de cómo termina con valores negativos es si tiene un diálogo centrado grande pero el usuario final ha instalado varias barras de herramientas y / o aumentado su fuente predeterminada -- en tal caso, la caja de cierre en un diálogo modal (si está en la parte superior) podría no ser visible y no se puede hacer clic.

La otra cosa que hago es acelerar esto un poco al almacenar en caché el objeto window(window) para reducir los traversals DOM adicionales y usar un CSS de clúster.

jQuery.fn.center = function ($) {
  var w = $(window);
  this.css({
    'position':'absolute',
    'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
    'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
  });
  return this;
}

Para usar, usted haría algo como:

jQuery(document).ready(function($){
  $('#myelem').center();
});
 14
Author: Volomike,
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-17 05:02:08

Me gustaría utilizar el jQuery UI position la función.

Ver demostración de trabajo.

<div id="test" style="position:absolute;background-color:blue;color:white">
    test div to center in window
</div>

Si tengo un div con id "test" para centrar, entonces el siguiente script centraría el div en la ventana de document ready. (los valores predeterminados para "my" y "at" en las opciones de posición son "center")

<script type="text/javascript">
$(function(){
  $("#test").position({
     of: $(window)
  });
};
</script>
 11
Author: andy_edward,
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-03 12:22:40

Me gustaría corregir una cuestión.

this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");

El código anterior no funcionará en los casos en que this.height (supongamos que el usuario cambia el tamaño de la pantalla y el contenido es dinámico) y scrollTop() = 0, por ejemplo:

window.height es 600
this.height es 650

600 - 650 = -50  

-50 / 2 = -25

Ahora la caja está centrada -25 fuera de la pantalla.

 8
Author: John Butcher,
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-03 12:17:38

No creo que tener una posición absoluta sería mejor si quieres un elemento siempre centrado en el centro de la página. Probablemente quieras un elemento fijo. Encontré otro plugin de centrado de jquery que usaba posicionamiento fijo. Se llama centro fijo.

 6
Author: Fred,
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
2010-07-03 09:25:23

Esto no está probado, pero algo como esto debería funcionar.

var myElement = $('#myElement');
myElement.css({
    position: 'absolute',
    left: '50%',
    'margin-left': 0 - (myElement.width() / 2)
});
 5
Author: Andrew Hedges,
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
2008-10-17 03:45:39

El componente de transición de esta función funcionó muy mal para mí en Chrome (no prueba en otro lugar). Cambiaba el tamaño de la ventana un montón y mi elemento se movía lentamente, tratando de ponerse al día.

Así que la siguiente función comenta esa parte. Además, agregué parámetros para pasar booleanos x e y opcionales, si desea centrar verticalmente pero no horizontalmente, por ejemplo:

// Center an element on the screen
(function($){
  $.fn.extend({
    center: function (x,y) {
      // var options =  $.extend({transition:300, minX:0, minY:0}, options);
      return this.each(function() {
                if (x == undefined) {
                    x = true;
                }
                if (y == undefined) {
                    y = true;
                }
                var $this = $(this);
                var $window = $(window);
                $this.css({
                    position: "absolute",
                });
                if (x) {
                    var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();
                    $this.css('left',left)
                }
                if (!y == false) {
            var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop();   
                    $this.css('top',top);
                }
        // $(this).animate({
        //   top: (top > options.minY ? top : options.minY)+'px',
        //   left: (left > options.minX ? left : options.minX)+'px'
        // }, options.transition);
        return $(this);
      });
    }
  });
})(jQuery);
 4
Author: Eric D. Fields,
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
2010-03-31 12:41:22

Editar:

Si la pregunta me enseñó algo, es esto: no cambies algo que ya funciona:)

Estoy proporcionando una copia (casi) literal de cómo se manejó esto en http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - está muy hackeado para IE, pero proporciona una forma CSS pura de responder a la pregunta:

.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper    {#position:absolute; #top:50%;
            display:table-cell; vertical-align:middle;}
.content   {#position:relative; #top:-50%;
            margin:0 auto; width:200px; border:1px solid orange;}

Violín: http://jsfiddle.net/S9upd/4/

He corrido esto a través de browsershots y parece bien; si por nada de lo contrario, mantendré el original a continuación para que el manejo del porcentaje de margen según lo dictado por las especificaciones CSS vea la luz del día.

Original:

Parece que llego tarde a la fiesta!

Hay algunos comentarios anteriores que sugieren que esta es una pregunta CSS - separación de preocupaciones y todo. Permítanme prefacio esto diciendo que CSS realmente se disparó en el pie en este caso. Quiero decir, qué fácil sería hacer esto:

.container {
    position:absolute;
    left: 50%;
    top: 50%;
    overflow:visible;
}
.content {
    position:relative;
    margin:-50% 50% 50% -50%;
}

¿Correcto? Esquina superior izquierda del contenedor estaría en el centro de la pantalla, y con márgenes negativos el contenido reaparecerá mágicamente en el centro absoluto de la página! http://jsfiddle.net/rJPPc /

Mal! El posicionamiento horizontal está bien, pero verticalmente... Oh, ya veo. Aparentemente en css, al establecer los márgenes superiores en%, el valor se calcula como un porcentaje siempre relativo al ancho del bloque contenedor. ¡Como manzanas y naranjas! Si no confías en mí o en Mozilla doco, juega con el violín de arriba ajustando el ancho del contenido y sorpréndete.

...

Ahora, con CSS siendo mi pan y mantequilla, no estaba a punto de rendirme. Al mismo tiempo, prefiero las cosas fáciles, por lo que he tomado prestados los hallazgos de un gurú CSS checo y lo convertí en un violín de trabajo. En resumen, creamos una tabla en la que vertical-align se establece en middle:

<table class="super-centered"><tr><td>
    <div class="content">
        <p>I am centered like a boss!</p>
    </div>
</td></tr></table>

Y que la posición del contenido está afinada con el buen viejo margen: 0 auto;:

.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}​

Violín de trabajo como se prometió: http://jsfiddle.net/teDQ2 /

 4
Author: o.v.,
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-20 03:40:45

Para centrar el elemento en relación con la ventana del navegador, no use position: absolute, el valor de posición correcto debe ser fixed (absoluto significa: "El elemento está posicionado en relación con su primer elemento antepasado posicionado (no estático)").

Esta versión alternativa del plugin de centro propuesto usa " % "en lugar de" px", por lo que cuando redimensiona la ventana, el contenido se mantiene centrado:

$.fn.center = function () {
    var heightRatio = ($(window).height() != 0) 
            ? this.outerHeight() / $(window).height() : 1;
    var widthRatio = ($(window).width() != 0) 
            ? this.outerWidth() / $(window).width() : 1;

    this.css({
        position: 'fixed',
        margin: 0,
        top: (50*(1-heightRatio)) + "%",
        left: (50*(1-widthRatio))  + "%"
    });

    return this;
}

Debe poner margin: 0 para excluir los márgenes de contenido del ancho / alto (ya que están utilizando la posición fija, tener márgenes no tiene sentido). De acuerdo con el documento jQuery usando .outerWidth(true) debe incluir márgenes, pero no funcionó como se esperaba cuando lo intenté en Chrome.

El 50*(1-ratio) viene de:

Ancho de la ventana: W = 100%

Ancho del elemento (en %): w = 100 * elementWidthInPixels/windowWidthInPixels

Para calcular el centrado a la izquierda:

 left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
 = 50 * (1-elementWidthInPixels/windowWidthInPixels)
 4
Author: Diego,
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-06-06 16:57:17

, Esto es genial. He añadido una función de devolución de llamada

center: function (options, callback) {


if (options.transition > 0) {
   $(this).animate(props, options.transition, callback);
} else { 
    $(this).css(props);
   if (typeof callback == 'function') { // make sure the callback is a function
       callback.call(this); // brings the scope to the callback
   }
}
 4
Author: Keith,
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-12-23 09:52:38

Lo que tengo aquí es un método de "centro" que asegura que el elemento que está intentando centrar no solo es de posicionamiento "fijo" o "absoluto", sino que también asegura que el elemento que está centrando es más pequeño que su padre, este centra y el elemento relativo a es padre, si los elementos padre es más pequeño que el elemento en sí, saqueará el DOM al siguiente padre, y lo centrará en relación a eso.

$.fn.center = function () {
        /// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>

        var element = $(this),
            elementPos = element.css('position'),
            elementParent = $(element.parent()),
            elementWidth = element.outerWidth(),
            parentWidth = elementParent.width();

        if (parentWidth <= elementWidth) {
            elementParent = $(elementParent.parent());
            parentWidth = elementParent.width();
        }

        if (elementPos === "absolute" || elementPos === "fixed") {
            element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
        }
    };
 3
Author: Ryan,
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-08-14 13:09:19

Yo uso esto:

$(function() {
   $('#divId').css({
    'left' : '50%',
    'top' : '50%',
    'position' : 'absolute',
    'margin-left' : -$('#divId').outerWidth()/2,
    'margin-top' : -$('#divId').outerHeight()/2
  });
});
 2
Author: holden,
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-11-01 12:07:15

Por favor use esto:

$(window).resize(function(){
    $('.className').css({
        position:'absolute',
        left: ($(window).width() - $('.className').outerWidth())/2,
        top: ($(window).height() - $('.className').outerHeight())/2
    });
});

// To initially run the function:
$(window).resize();
 2
Author: satya,
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-19 21:06:43

Está obteniendo esa transición pobre porque está ajustando la posición del elemento cada vez que se desplaza el documento. Lo que quieres es usar posicionamiento fijo. Probé ese plugin de centro fijo mencionado anteriormente y eso parece resolver el problema muy bien. El posicionamiento fijo le permite centrar un elemento una vez, y la propiedad CSS se encargará de mantener esa posición cada vez que se desplace.

 0
Author: skaterdav85,
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
2010-07-07 18:17:19

Aquí está mi versión. Puedo cambiarlo después de mirar estos ejemplos.

$.fn.pixels = function(property){
    return parseInt(this.css(property));
};

$.fn.center = function(){
    var w = $($w);
    return this.each(function(){
        $(this).css("position","absolute");
        $(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
        $(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
    });
};
 0
Author: Andrew Anthony Gerst,
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-06-04 14:54:05

No necesita jquery para esto

Usé esto para centrar el elemento Div. Estilo Css,

.black_overlay{
    display: none;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}

.white_content {
    display: none;
    position: absolute;
    top: 25%;
    left: 25%;
    width: 50%;
    height: 50%;
    padding: 16px;
    border: 16px solid orange;
    background-color: white;
    z-index:1002;
    overflow: auto;
}

Elemento abierto

$(document).ready(function(){
    $(".open").click(function(e){
      $(".black_overlay").fadeIn(200);
    });

});
 0
Author: Sajitha Nilan,
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-10-17 10:21:24

MI ACTUALIZACIÓN A LA RESPUESTA DE TONY L Esta es la versión modificada de su respuesta que uso religiosamente ahora. Pensé que lo compartiría, ya que agrega un poco más de funcionalidad para varias situaciones que pueda tener, como diferentes tipos de position o solo desea centrado horizontal/vertical en lugar de ambos.

Centro.js:

// We add a pos parameter so we can specify which position type we want

// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
    this.css("position", pos);
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it vertically only
jQuery.fn.centerVer = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    return this;
}

En mi <head>:

<script src="scripts/center.js"></script>

Ejemplos de uso:

$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")

$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")

$("#example5").center("absolute")
$("#example6").center("fixed")

Funciona con cualquier tipo de posicionamiento, y se puede utilizar en todo su todo el sitio fácilmente, así como fácilmente portátil a cualquier otro sitio que cree. No más soluciones molestas para centrar algo correctamente.

Espero que esto sea útil para alguien por ahí! Disfrutar.

 0
Author: Fata1Err0r,
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-07-23 15:31:33

Hay muchas maneras de hacer esto. Mi objeto se mantiene oculto con display:none justo dentro de la etiqueta BODY para que el posicionamiento sea relativo al CUERPO. Después de usar $("#object_id").show () , llamo a $("#object_id").centro()

Utilizo position: absolute porque es posible, especialmente en un dispositivo móvil pequeño, que la ventana modal sea más grande que la ventana del dispositivo, en cuyo caso parte del contenido modal podría ser inaccesible si el posicionamiento fuera fijo.

Aquí está mi sabor basado en las respuestas de otros y mis necesidades específicas:

$.fn.center = function () {
        this.css("position","absolute");

        //use % so that modal window will adjust with browser resizing
        this.css("top","50%");
        this.css("left","50%");

        //use negative margin to center
        this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
        this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");

        //catch cases where object would be offscreen
        if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
        if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});

        return this;
    };
 0
Author: i_a,
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-09-30 23:15:55

Normalmente, haría esto solo con CSS... pero ya que le pidió una manera de hacer esto con jQuery...

El siguiente código centra un div tanto horizontal como verticalmente dentro de su contenedor:

$("#target").addClass("centered-content")
            .wrap("<div class='center-outer-container'></div>")
            .wrap("<div class='center-inner-container'></div>");
body {
    margin : 0;
    background: #ccc;
}

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

.center-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;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="target">Center this!</div>

(véase también este Violín)

 0
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-16 16:27:02

Solución CSS Solo en dos líneas

Centraliza tu div interior horizontal y verticalmente.

#outer{
  display: flex;
}
#inner{
margin: auto;

}

Para alinear solo horizontal, cambiar

margin: 0 auto;

Y para vertical, cambiar

margin: auto 0;
 0
Author: Shivam Chhetri,
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-15 18:21:23

No te recomendaría usar jQuery para centrar el contenedor, porque es demasiado pesado para ser calculado y depende del JavaScript. Por ejemplo, si diseña una página simple, ¿necesitará cargar jQuery solo para centrar un nodo de elemento "div"?

El siguiente código resuelve el problema propuesto usando características "table". Se calcula exactamente sin causar ningún problema de visualización:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Centering issue</title>
        <style>
            html,body {
                padding: 0;
                margin: 0;
                height: 100%
            }
            .outer {
                display: table;
                width: 100%;
                height: 100%;
                border-collapse: collapse
            }
            .inner {
                display: table-cell;
                vertical-align: middle
            }
            #sample {
                margin: 0 auto;
                text-align: center;
                line-height: 100px;
                width: 100px;
                height: 100px;
                background: #ccc
            }
        </style>
    </head>
    <body>
        <div class="outer">
            <div class="inner">
                <div id="sample">Sample</div>
            </div>
        </div>
    </body>
</html>

El siguiente soluciona el mismo problema propuesto usando el nuevo concepto flexbox. También calculado exactamente sin causar ningún problema de visualización. Prefiero la disposición "tabla" (la anterior) en lugar de esta solución, porque tiene mejor compatibilidad con navegadores muy antiguos y, por lo tanto, cubre aún más clientes sin ningún problema.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Centering issue</title>
        <style>
            html,body {
                padding: 0;
                margin: 0;
                height: 100%
            }
            .centerer {
                display: flex;
                align-items: center;
                justify-content: space-around;
                height: 100%
            }
            #sample {
                margin: 0 auto;
                text-align: center;
                line-height: 100px;
                width: 100px;
                height: 100px;
                background: #ccc
            }
        </style>
    </head>
    <body>
        <div class="centerer">
            <div id="sample">Sample</div>
        </div>
    </body>
</html>

Espero que esta sugerencia te ayude. :)

Adiós

 0
Author: Recovieira Coimbra Vieira,
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-12 23:31:24

Puedes usar la propiedad CSS translate:

position: absolute;
transform: translate(-50%, -50%);

Lee este post para más detalles.

 -1
Author: Fred K,
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-27 17:31:48

¿Por qué no usas CSS para centrar un div?

#timer_wrap{  
  position: fixed;
  left: 50%;
  top: 50%;
} 
 -6
Author: ahmad balavipour,
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-07-26 22:20:17