Reputation: 598
I am trying to center a series of SPANs vertically inside their parent LIs.
The height values returned are all the same which means there must be something wrong with this code as some of the spans are on two lines.
Not sure if getting the height of an inline element (span) is a problem, any suggestions appreciated.
HTML:
<li class="nav-level-2-item">
<a href="">
<span class="menu-item">Text</span>
</a>
</li>
<li class="nav-level-2-item">
<a href="">
<span class="menu-item">Longer Text</span>
</a>
</li>
</ul>
JS:
$(document).ready(function () {
var navItem = $('li.nav-level-2-item');
navItem.each(function() {
var containerHeight = $('li.nav-level-2-item').height();
var spanHeight = $('span.menu-item').height();
alert(spanHeight)
$('span.menu-item').css('top', (containerHeight - spanHeight) / 2);
});
});
Upvotes: 2
Views: 3548
Reputation: 5977
I'm not sure whether this is applicable to your code, but maybe you could avoid using jQuery altogether by making the <li>
elements inline-block and centering them vertically:
li.nav-level-2-item
{
display: inline-block;
*display: inline; *zoom: 1; /* IE 6-7 hack */
vertical-align: middle;
}
Or another possible solution:
li.nav-level-2-item
{
display: table;
}
li.nav-level-2-item a
{
display: table-cell;
vertical-align: middle;
}
For additional CSS-only solutions, check out http://phrogz.net/css/vertical-align and http://www.vanseodesign.com/css/vertical-centering.
Upvotes: 1
Reputation: 27012
I'm not sure what the goal is, but I do have an answer for why the alert is always the same. You're iterating the li
elements with .each()
, but on each iteration, you aren't referencing the current item, so you always retrieve the height of the first matching element. Try this:
$(document).ready(function () {
var navItem = $('li.nav-level-2-item');
navItem.each(function() {
var containerHeight = $(this).height();
var spanHeight = $('span.menu-item', this).height();
console.log(spanHeight)
});
});
Vertical centering of menu items is probably going to be easier by setting the line-height
.
Upvotes: 1
Reputation: 35407
Making your span a block-level element will give it height
:
<style> span.menu-item { display:block /* or inline-block */; } </style>
As an alternative, you could change the span to be one of the native block-level elements.
Upvotes: 2