我有一个DIV,我希望文本在该div中垂直居中。我不能使用固定像素高度,只能使用百分比。
<div style="position:relative; width: 100%; height: 100%;">
<img src="images/thumb-member-placeholder.gif" alt="" class="myImage" />
<div class="myText" style="display: inline-block; position: absolute; z-index:500; text-align:center;">Image Text</div>
</div>
我有100个这样的div,其中“myText”可以是1行或3行。
所以我使用jquery来检测高度并相应地设置TOP值:
$(window).load(function() {
var imageHeight = $('.myImage').height();
$('.myText').each(function() {
var textHeight = $('.myText').height();
var vertAdj = ((imageHeight - textHeight) / 2);
$(this).css('top', vertAdj);
});
});
但它不起作用。它始终输出相同的TOP值,当文本变为2或3行时,不会检测到“myText”的高度。
有什么建议吗?
答案 0 :(得分:2)
试试这个:
$('.myText').each(function(index,element) {
var textHeight = $(element).height();
var vertAdj = ((imageHeight - textHeight) / 2);
$(element).css('top', vertAdj);
});
请参阅.each
文档了解更多http://api.jquery.com/each/