jQuery: Animating width/height, but Stay Centered

12,048

Live Demo

var growEl = $("#grow"),
    curHeight = $("#grow").height(),
    curTop = growEl.offset().top,
    newHeight = 200,
    newMargin = curTop -(newHeight -curHeight)/2;

if(newMargin < 0){
 newMargin = 0;   
}

$("#grow").animate({height:newHeight+"px", marginTop:newMargin + 'px'});

Formula for figuring out what to make the margin

NewTopMargin = CurrentMargin-(NewHeight-OldHeight)/2

Thanks @bobsoap for reminding me to use offset.top

Share:
12,048
mellowsoon
Author by

mellowsoon

Updated on June 14, 2022

Comments

  • mellowsoon
    mellowsoon almost 2 years

    I have an element on the page that I've already centered horizontally and vertically (It's a jQuery UI Modal Dialog), and want to resize it using .animate() like this:

    <div id="element" style="width: 100px; height: 100px;">
        Hi Stack Overflow!
    </div>
    
    <script type="text/javascript">
        $('#element').animate({ height: "200px" });
    </script>
    

    That works fine, except the element only grows downwards. What I'm trying to do is have the element grow vertically in both directions (in this case 50px in each direction) so it stays centered. Is there a way that it can be done?

  • mellowsoon
    mellowsoon about 13 years
    That's what I tried at first, but I discovered a flaw. The new top margin may be a negative number if the browser window is small. In that case, the element should grow up as much as it can (with a margin), and down the rest of the way. I was hoping there wouldn't be a lot math or complicated animation calculations. I want to keep this thing speedy.
  • bobsoap
    bobsoap about 13 years
    @mellowsoon you can get the position of the element with offset, then access it with offset.top. You can't get around doing some math, but it's not a "complicated animation calculation" anyway. You first do some basic math, which JS is fast at, then you do a single animate() function, which you're doing already.
  • Loktar
    Loktar about 13 years
    Updated again, to use offset().top.
  • klewis
    klewis almost 8 years
    Awesome answer, how can we get the text vertically aligned center the whole time, while the box expands?