Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change the top margin of a div based on its height

Tags:

jquery

I have a div that is fixed to the side of my web page. I need that div to be centered vertically. Easily accomplished using CSS: (note: the base height of the div is 300px;)

#sidePanel { margin: -150px 0 0 0; top: 50%; position: fixed;}

The issue I'm having is this sidePanel div holds my site navigation. When the nav opens up to show child elements, it grows in height which messes up the centering. I need some jQuery to re-calculate the height of the sidePanel div and the apply the appropriate negative margin to keep the div centered. Here is the jQuery I was playing with:

$("#sidePanel").css("margin-top", $(this).outerHeight());

I have not worked on the calculation to set the negaitve margin to half of the height, but this is not giving me the height value I'm looking for. Any suggestions??

like image 899
Mike Muller Avatar asked Dec 18 '25 00:12

Mike Muller


1 Answers

this doesn't refer to the #sidePanel element in this case, you would need to either make it with a function passed into .css() like this:

$("#sidePanel").css("margin-top", function() { return $(this).outerHeight() });

Or a .each() call, like this:

$("#sidePanel").each(function() {
  $(this).css("margin-top", $(this).outerHeight());
});

Or cache the selector, like this:

var sp = $("#sidePanel");
sp.css("margin-top", sp.outerHeight());
like image 166
Nick Craver Avatar answered Dec 19 '25 18:12

Nick Craver