Mike Muller
Mike Muller

Reputation: 2297

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

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??

Upvotes: 3

Views: 22441

Answers (2)

Aaron Hathaway
Aaron Hathaway

Reputation: 4315

Try setting the margin to the window's height minus the div's height, all divided by two. That should center it vertically.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630569

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());

Upvotes: 6

Related Questions