根据其高度动态更改div的上边距 [英] Dynamically change the top margin of a div based on its height
问题描述
我的div固定在网页的侧面.我需要将该div垂直居中.使用CSS可以轻松完成:(请注意:div的基本高度为300px;)
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;}
我遇到的问题是该sidePanel div保存了我的网站导航.导航打开以显示子元素时,其高度会增加,从而使居中混乱.我需要一些jQuery重新计算sidePanel div的高度,并应用适当的负边距以使div居中.这是我正在使用的jQuery:
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??
推荐答案
this
不引用#sidePanel
元素,您需要通过传递给 .css()
像这样:
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() });
或 .each()
调用,如下所示:
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());
这篇关于根据其高度动态更改div的上边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!