div align jquery centering

jquery - align - center image in div



Centrar un div verticalmente y horizontalmente usando jQuery (9)

Estoy usando este script para centrar mi div horizontal y verticalmente.

Cuando la página carga el div se centra verticalmente, no horizontalmente hasta que cambie el tamaño del navegador.

¿Qué estoy haciendo mal?

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


En relación con su fragmento de código, primero debe establecer la posición:

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

Tal vez podría establecer el atributo de posición a través de un estilo CSS estático .


Envuelva el código del controlador en una función para que pueda invocar esa función tanto en la carga de la página como en el controlador de $(window).resize()

/* use as handler for resize*/ $(window).resize(adjustLayout); /* call function in ready handler*/ $(document).ready(function(){ adjustLayout(); /* your other page load code here*/ }) function adjustLayout(){ $(''.className'').css({ position:''absolute'', left: ($(window).width() - $(''.className'').outerWidth())/2, top: ($(window).height() - $(''.className'').outerHeight())/2 }); }


Normalmente uso esta "técnica":

$(function() { $(''.className'').css({ ''position'' : ''absolute'', ''left'' : ''50%'', ''top'' : ''50%'', ''margin-left'' : -$(''.className'').width()/2, ''margin-top'' : -$(''.className'').height()/2 }); });

ACTUALIZAR:

Estoy actualizando la solución, como lo sugirió el usuario Fred K , usando .outerWidth() y .outerHeight() para tener un centrado más preciso.

$(function() { $(''.className'').css({ ''position'' : ''absolute'', ''left'' : ''50%'', ''top'' : ''50%'', ''margin-left'' : -$(''.className'').outerWidth()/2, ''margin-top'' : -$(''.className'').outerHeight()/2 }); });

Algunas notas adicionales de la documentación de jQuery ( .outerWidth() , .outerHeight() ):

  • El número devuelto por las API relacionadas con las dimensiones, incluido .outerWidth (), puede ser fraccionario en algunos casos. El código no debe suponer que es un número entero. Además, las dimensiones pueden ser incorrectas cuando el usuario amplía la página; los navegadores no exponen una API para detectar esta condición.

  • No se garantiza que el valor informado por .outerWidth () sea preciso cuando el elemento principal del elemento oculto. Para obtener un valor preciso, primero debe mostrar el padre antes de usar .outerWidth ().

ACTUALIZACIÓN 2:

Una simple actualización para mostrar cómo puede usar this dentro del método css() en caso de que haya más elementos con la misma etiqueta de class con diferentes tamaños.

$(function() { $(''.className'').css({ ''position'' : ''absolute'', ''left'' : ''50%'', ''top'' : ''50%'', ''margin-left'' : function() {return -$(this).outerWidth()/2}, ''margin-top'' : function() {return -$(this).outerHeight()/2} }); });



Recientemente he estado tratando de colocar una caja en el medio de una ventana del navegador. Creé el código a continuación. La secuencia de comandos de jQuery es bastante larga porque tomé en cuenta todas las separaciones y los márgenes de las etiquetas html y body, si alguien las configuró. Si a uno no le importan los fondos, solo se deben establecer winwidth, winheight, toppx, leftpx y "#container". El resto puede ser eliminado.

<!DOCTYPE html> <html> <head> <title>Test of centre of container</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <style> html { background-color: #444; margin: 30px; } #wrapper { background-color: #777; width: 75%; margin: 0 auto; padding: 0; } #container { background-color: #ddd; border-radius: 10px; box-shadow: 0 0 2px #222; width: 200px; height: 100px; position: absolute; vertical-align: middle; } #extext { text-align: center; padding: 0; } </style> </head> <body> <script> function setDimensions() { var winwidth = $(window).width(); var winheight = $(window).height(); var htmlmv = parseInt($("html").css("margin-top")) + parseInt($("html").css("margin-bottom")); var htmlpv = parseInt($("html").css("padding-top")) + parseInt($("html").css("padding-bottom")); var htmlmh = parseInt($("html").css("margin-left")) + parseInt($("html").css("margin-right")); var htmlph = parseInt($("html").css("padding-left")) + parseInt($("html").css("padding-right")); var bodymv = parseInt($("body").css("margin-top")) + parseInt($("body").css("margin-bottom")); var bodypv = parseInt($("body").css("padding-top")) + parseInt($("body").css("padding-bottom")); var bodymh = parseInt($("body").css("margin-left")) + parseInt($("body").css("margin-right")); var bodyph = parseInt($("body").css("padding-left")) + parseInt($("body").css("padding-right")); var vspace = htmlmv + htmlpv + bodymv + bodypv; var hspace = htmlmh + htmlph + bodymh + bodyph; var wrapheight = winheight - vspace; var wrapwidth = winwidth - hspace; $("#wrapper").height(wrapheight); // $("#wrapper").width(wrapwidth); var toppx = (winheight - parseInt($("#container").css("height"))) / 2; var leftpx = (winwidth - parseInt($("#container").css("width"))) / 2; $("#container").css("top", toppx.toString() + "px"); $("#container").css("left", leftpx.toString() + "px"); } $(document).ready(function () { setDimensions(); }); $(window).resize(function () { setDimensions(); }); </script> <div id="wrapper"> <div id="container"> <p id="extext">Example text</p> </div> </div> </body> </html>




EDITAR: Encontré una solución mucho mejor para esto en el sitio web CSS Tricks y solo usa CSS :). El código a continuación:

<!DOCTYPE html> <html> <head> <title> Test centring! </title> <style> body div { background-color: red; box-shadow: 0 0 15px #222; border-radius: 10px; padding: 10px; margin: -150px auto auto -200px; width: 380px; height: 280px; position: absolute; top: 50%; left: 50%; text-align: center; line-height: 140px; } body div h2 { color: yellow; margin: 0; padding: 0; } </style> </head> <body> <div> <h2> Example text<br /> Example Text </h2> </div> </body> </html>


Utilizo este plugin JQuery.center para centrar mis elementos DOM. El código será algo como esto:

$("#child").center()

El código anterior se centrará en relación con su padre directo, si necesita centrarse en relación con otro padre, será:

$("#child").center($("#parent"))

Hay opciones personalizadas, si necesita otra forma de centralización.


basado en la respuesta de @dimi, funciona mejor con múltiples elementos

$(".className").each( function () { $( this ).css("position","absolute"); $( this ).css("left","50%"); $( this ).css("margin-left", - $( this ).outerWidth()/2 ); $( this ).css("top","50%"); $( this ).css("margin-top", - $( this ).outerHeight()/2 ); return this; } );


mi div con centro de clase tiene que estar centrado horizontalmente en el centro y su posición es fija. Utilizo este pequeño código para hacerlo realidad:

$(window).on(''resize load'', function () { $(''.center'').each(function () { $(this).css({ ''margin-left'': ($(''body'').width() - $(this).width()) / 2 }); }); });

también puedes usar las mismas tácticas para la alineación horizontal. Eche un vistazo que maneja de una vez al cargar y al cambiar el tamaño de los eventos, por lo que este div siempre está en el medio.


usa esto para centrar:

$.fn.center = function () { this.css("position","absolute"); this.css("top", ( $(window).height() - this.height() ) / 2 + "px"); this.css("left", ( $(window).width() - this.width() ) / 2 + "px"); return this; } $(''yourElem'').center();