Immaginiamo di avere un elemento genitore posizionato in modo assoluto e di eseguire una richiesta AJAX che inserirà un elemento dalle dimensioni che non possiamo conoscere in anticipo all'interno dell'elemento posizionato. Come possiamo centrare verticalmente ed orizzontalmente questo elemento con jQuery?
Definiamo il seguente plugin:
(function( $ ) {
$.fn.center = function ( parent ) {
this.css( "position", "absolute" );
var position = parent.position();
this.css( "top", Math.max( 0, ( ( parent.height() - this.outerHeight() ) / 2 ) + position.top ) + "px" );
this.css( "left", Math.max( 0, (( parent.width() - this.outerWidth() ) / 2 ) + position.left ) + "px" );
return this;
};
})( jQuery );
Esempio d'uso:
$.get( "ajax.php", function( html ) {
var $parent = $( "#test" );
$( html ).
appendTo( $parent ).center( $parent );
});