Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center background image from sprite

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?

like image 297
user1292810 Avatar asked Dec 12 '22 13:12

user1292810


1 Answers

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. */

}
like image 129
brentonstrine Avatar answered Dec 26 '22 04:12

brentonstrine