I have the following div :
<div id = "shrink-test" style = "position:absolute;top:100px;left:50%;margin-left:-50px;height:100px;width:100px;background-color: red;" />
and I want to use jQuery's animate()
to shrink the div to half of its size but keep the animation and position of my div centered.
I'm trying:
$("#shrink-test").animate(
{
height: 50,
width: 50
});
but it shrinks the div using its top left corner as reference. How can I make it use its center as the reference point?
Thanks for any help!
As your div is positioned absolutely by using top
and margin-left
, you will need to animate those as well:
$("#shrink-test").animate({
height: 50,
top: 125, // 100 + 50 / 2
width: 50,
marginLeft: -25 // 50 / -2
});
For a programmatical approach it might be easier to use a negative margin for the y-axis, too.
Here's just a simple jQuery plugin for this
$.fn.resize = function( w, h ) {
w = ( undefined !== w ? w : 50 );
h = ( undefined !== h ? h : 50 );
var cw = this.width();
var ch = this.height();
if ( 'static' === this.css( 'position' ) ) {
this.css( {
'position' : 'relative',
'top' : '0px',
'left' : '0px'
} );
}
this.stop().width( cw ).height( ch ).animate( {
'top' : '+=' + ( (ch - h) / 2 ) + 'px',
'left' : '+=' + ( (cw - w) / 2 ) + 'px',
'width' : w + 'px',
'height' : h + 'px'
} );
};
$( function() {
$( '#shrink-test' ).resize(50,50);
} );
Test it here: http://jsfiddle.net/bukfixart/nPjMa/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With