I ha开发者_如何学编程ve a div that can have various heights based on the size of the text within it. I use jquery to show it when a user hovers over an icon. I want the div to appear vertical center to that icon. I can't use the normal method of:
height: 100px; top: 50%; margin-top: -50px;
because I can't specify the height of the element due to the variations in height.
Any ideas on how I could do this? Thanks.
Here's a very straightforward solution that should work for any element height.
HTML:
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
jquery:
var margin = $('.container').height()/2;
$('.container').css({'margin-top' : -margin});
We get the height of the element, then divide it in half. We then set the margin-top to the negative of half of the height of the div.
精彩评论