csscss-sprites

CSS Sprite is not loading sprites correctly


I'm trying to load a spritesheet for a menu that I'm building, but instead of showing one image at a time, it shows the whole spritesheet at different positions in the element.

This is my CSS code using two images:

#mymenu ul.menu > li > a.haschild
{
    background: #000 url("../images/right.png") no-repeat right center;
}
    #mymenu ul.menu > li:hover > a.haschild
    {
        background: #000 url("../images/right-hover.png") no-repeat right center;
    }

This is what I've tried to use a spritesheet:

#mymenu ul.menu > li > a.haschild
{
    background: #000 url("../images/spritesheet.png") 0px 0px no-repeat right center;
}
    #mymenu ul.menu > li:hover > a.haschild
    {
        background: #000 url("../images/spritesheet.png") -6px 0px no-repeat right center;
    }

But it shows both images at the same time (the whole spritesheet)

I've also tried:

#mymenu ul.menu > li > a.haschild
{
    background: #000;
    background-image: url("../images/spritesheet.png") 0px 0px no-repeat right center;
}
    #mymenu ul.menu > li:hover > a.haschild
    {
        background: #000;
            background-image: url("../images/spritesheet.png") -6px 0px no-repeat right center;
    }

same result...

What am I doing wrong ?

EDIT

This is my jsFiddle:

http://jsfiddle.net/HKaSw/


Solution

  • You have to think of it like this: you're applying a background image to an element which is quite large. Your CSS doesn't know that the background image is a sprite; it just displays the background image like any other background image. And in your case, the icons are right next to each other on the image, so they get displayed as a whole. You cannot crop just part of a background image using css, so you either need to include ample padding in the sprite to account for the size of the element (tricky, because you may want to use the icons on even larger elements, which is an unknown), or include extra elements in your markup that fit to the exact size of the icons, then add the icon sprite to them (more foolproof, but extra markup sucks).

    Here's an example of the code, and I removed some of the extraneous CSS (I'm sure it can be optimised further, but we're just working on the icons here). You don't need to define the icon class on both parent and sub-menu items; you can re-use the icon class. That's the point of CSS!

    a.haschild i {
      background: #000 url("http://www.grouctivity.com/menu/sprites.png") no-repeat 0 0;
    }
    
    a.haschild:hover i {
      background-position: -6px 0;
    }
    

    Here's a jsFiddle with a demo of the extra icon elements: http://jsfiddle.net/HKaSw/2/