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

I have a div that is anchored to the side of my webpage. I need the div to be centered vertically. Easy to do with CSS: (note: the height of the base of the div is 300px;)

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

The problem I am facing is that this sidePanel div supports my site navigation. When the navigator opens to display children, it grows in height, which leads to centering. I need some jQuery to recount the height of the sidePanel div and apply the corresponding negative margin to keep the div in the center. Here is the jQuery I played with:

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

I have not worked on the calculation to set the negaitve marker to half height, but this does not give me the height value that I am looking for. Any suggestions?

+3
source share
2 answers

thisnot relevant to the element #sidePanelin this case, you need to either do it using the function passed to .css():

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

Or .each()like this:

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

Or cache the selector, for example:

var sp = $("#sidePanel");
sp.css("margin-top", sp.outerHeight());
+6
source

Try setting the margin to the height of the window minus the height of the div, all divided by two. This should center it vertically.

0
source

Source: https://habr.com/ru/post/1774194/


All Articles