How can I make all the elements from this list have the background in center no matter of the width of the element.
<ul id="menu">
<li><a href="#">Name</a></li>
<li><a href="#">Name</a></li>
<li><a href="#">Name</a></li>
<li><a href="#">Name</a></li>
<li><a href="#">Name</a></li>
</ul>
My css is like this:
ul#menu li a { background:url(../images/header-img.png) 0 0 no-repeat; padding:40px 0 0 0; display:block; font-size:12px; color:#000;}
I tried like this, but no luck:
$("ul#menu li a").each(function(i){
var value = $(this).width()/2;
$(this).css('backgroundPosition', value + ' 0');
});
Thank you!
Well Florescu,
I finally figured it out.
The problem is that links don’t have any width, firebug ’em and you’ll see that their width is computed as ‘auto’ unless you promote them to block level elements with explicit widths. So the solution? We find the width of the text contained in ’em.
Here’s the solution, http://jsfiddle.net/aPuhP/1/; and the explanation,
We insert a dummy span tag to be able to calculate the element’s width,
..we then calculate the width and run calculations required to get the desired width (the -20 is to compensate for the sprite’s distance from the left edge of the image),
..and finally, we get rid of the dummy span tag,
Hope this helps.
PS: Kudos to Calculating text width.