67

I want to reposition an entire div and its contents up about 10-15 pixels.

How can I do this?

Note: this is slider element, so when I click a button the slider slides down. Once it is finished I want to reposition it up about 15 pixels.

codecompleting
  • 9,251
  • 13
  • 61
  • 102

4 Answers4

64
$('#div_id').css({marginTop: '-=15px'});

This will alter the css for the element with the id "div_id"

To get the effect you want I recommend adding the code above to a callback function in your animation (that way the div will be moved up after the animation is complete):

$('#div_id').animate({...}, function () {
    $('#div_id').css({marginTop: '-=15px'});
});

And of course you could animate the change in margin like so:

$('#div_id').animate({marginTop: '-=15px'});

Here are the docs for .css() in jQuery: http://api.jquery.com/css/

And here are the docs for .animate() in jQuery: http://api.jquery.com/animate/

Jasper
  • 75,717
  • 14
  • 151
  • 146
  • 1
    @Kira The `duration` argument can be passed after the `properties` argument. It should be an integer and defaults to `400`: http://api.jquery.com/animate/ – Jasper Dec 03 '18 at 19:27
  • It's a bad idea to animate `margin` property, because it changes the elements layout and causes reflow. The much better idea would be to use `transform-translate` property for animation with CSS transition. – Slava Fomin II Jan 25 '20 at 23:06
50
$('div').css({
    position: 'relative',
    top: '-15px'
});
gislikonrad
  • 3,401
  • 2
  • 22
  • 24
14

In css add this to the element:

margin-top: -15px; /*for exact positioning */
margin-top: -5%; /* for relative positioning */

you can use either one to position accordingly.

srinivas
  • 4,778
  • 2
  • 32
  • 43
0

you can also do this

margin-top:-30px; 
min-height:40px;

this "help" to stop the div yanking everything up a bit.

Mr Heelis
  • 2,370
  • 4
  • 24
  • 34