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.

2
  • You should mention whether or not it currently has any positioning CSS. That way you might be able to alter it (e.g. with javascript). Aug 22, 2011 at 19:33
  • 7
    Have you considered position: relative; top: -15px;?
    – Tejs
    Aug 22, 2011 at 19:33

4 Answers 4

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/

2
  • 1
    @Kira The duration argument can be passed after the properties argument. It should be an integer and defaults to 400: api.jquery.com/animate
    – Jasper
    Dec 3, 2018 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. Jan 25, 2020 at 23:06
50
$('div').css({
    position: 'relative',
    top: '-15px'
});
0
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.

1
  • This method works best, if you want to use only CSS Nov 30, 2019 at 21:24
0

you can also do this

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.