Search code examples
htmlcsscss-sprites

Using css sprites without html


I have created a css sprite image for multiple images. The css for sprite is:

.sprites {background-image:url("/images/max.png");background-color:transparent;background-repeat:no-repeat;}#image_5306605314403955_gif {height:10px;width:10px;background-position:0 0;}#image_2814089791124994_gif {height:8px;width:8px;background-position:-10px 0;}#image_05699283026450497_gif {height:36px;width:50px;background-position:-18px 0;}#image_23591702358881883_gif {height:9px;width:11px;background-position:-68px 0;}#image_9167572062810537_gif {height:10px;width:10px;background-position:-79px 0;}#image_21043553959746242_gif {height:16px;width:16px;background-position:-89px 0;}

Now I want to assign the first image from this sprite to an li element. Currently the first images is assigned using background:url property of this li as:

li{margin-top:0;padding:3px 0 3px 25px;background:url(../images/arrow.gif) 

How can bring the first image from sprite and assign to the li element. I have seen an example which suggests to use:

<div class="sprites" id="image_5306605314403955_gif"></div>

But I want to see if adding HTML can be avoided and use CSS only for that purpose. The li element on my page looks like:

<li><a href="http://www.xyz.com">ABC</a></li>

Solution

  • I am not sure if that is what you are looking for or not, but the below code should do it:

    HTML:

    <li class="sprites"><a id="image_5306605314403955_gif" href="http://www.xyz.com">ABC</a></li>
    <li class="sprites"><a id="#image_9167572062810537_gif" href="http://www.xyz.com">ABC</a></li>
    

    CSS:

    .sprites {background-image:url("/images/max.png");background-color:transparent;background-repeat:no-repeat;}
    #image_5306605314403955_gif {height:10px;width:10px;background-position:0 0;}
    #image_2814089791124994_gif {height:8px;width:8px;background-position:-10px 0;}
    #image_05699283026450497_gif {height:36px;width:50px;background-position:-18px 0;}
    #image_23591702358881883_gif {height:9px;width:11px;background-position:-68px 0;}
    #image_9167572062810537_gif {height:10px;width:10px;background-position:-79px 0;}
    #image_21043553959746242_gif {height:16px;width:16px;background-position:-89px 0;}
    

    If what you are looking for is not to use class or id, then I think it is impossible, as your CSS needs an identifier to differentiate between your items (which are inherited from the same class <li>)