-1

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!

Adrian Florescu
  • 4,454
  • 8
  • 50
  • 74

2 Answers2

1

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,

    var source = $(this).html();
    var sensor = "<span>" + source + "</span>";
    $(this).html(sensor);

..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),

   var width = $(this).find('span:first').outerWidth();
   var v = width/2;
   $(this).css('backgroundPosition', v - 20 + 'px 0');

..and finally, we get rid of the dummy span tag,

   $(this).html(source);

Hope this helps.

PS: Kudos to Calculating text width.

Community
  • 1
  • 1
Amit G
  • 1,338
  • 9
  • 15
0

you will have to take in consideration the 40 pixel wide padding given to the elements.

Horizontal value must be first, vertical value must be second in the css statement. If you use values smaller or greater than zero, you should add the measurement unit (px, pc, pt, em)

beerwin
  • 9,813
  • 6
  • 42
  • 57