Center background image from sprite

user1292810 picture user1292810 · Jul 1, 2013 · Viewed 9.9k times · Source

I have menu as follows:

<ul>
  <li><a href="#">First Item</a></li>
  <li><a href="#">Long Item</a></li>
  <li><a href="#">Very very short Item</a></li>
  <li><a href="#">Another Item</a></li>
  <li><a href="#">Last Item</a></li>
</ul>

I would like to use sprite image as background in CSS. I would like the image to be centered in different width menu items. Currently, for the first item correct CSS is:

background: url(images/sprite.png) no-repeat -20px -10px;

For the second:

background: url(images/sprite.png) no-repeat -24px -10px;

For the third:

background: url(images/sprite.png) no-repeat -32px -10px;

And so on. I don't know the exact width of each element, and it can change at any moment.

I have access to HTML structure, so I can add some tags if it is needed. Is it possible to center background image in that case?

Answer

brentonstrine picture brentonstrine · Jul 2, 2013

JSFiddle demo.

Basically, you create a pseudoelement, use position: absolute and left:50% to center it.

li a { position: relative;} /* makes the (position:absolute) below work */
li a:after{
    content: "";
    position: absolute;
    top: 0;
    left: 50%; /* centers the left edge of the sprite */
    margin-left: -8.5px; /* this centers the actual sprite--this is half the sprite-window width. if you don't do this, the left edge will be centered instead of the center of the sprite.  */
    width: 15px; /* set window to see sprite through */
    height: 18px; /* set window to see sprite through */
    background: url(https://www.google.com/images/nav_logo129.png) no-repeat -15px -327px; /*  set up the sprite. Obviously change this fto make each one different. */

}