Search code examples
csscss-sprites

How use CSS sprites?


I'm trying to figure out how to use CSS Sprites on a sprite image with 4 sprites.

I have code to show the first two sprites. I have trouble with writing code to show the last two sprites. I am also unable to show the third and 4th sprites by themselves.

This is the image: Wrestling items

How to show the last two? How to show the 3rd and 4th sprite by themselves?


Solution

  • HTML

    <div class="container">
        <ul>
            <li id="belt-1"></li>
            <li id="belt-2"></li>
            <li id="belt-3"></li>
            <li id="belt-4"></li>
        </ul>
    </div>
    

    CSS

    .container {
        position: relative;
        width: 600px;
        height: 600px;
    }
    
    .container ul {
        list-style: none;
        margin: 0;
        padding: 0;
    }
    
    .container ul li {
        background-image: url(https://i.sstatic.net/SBxX4.png);
        margin-bottom: 20px;
        width: 150px;
        height: 78px;
        background-size: auto 286px;
        background-position: 0 0;
    }
    
    .container ul li#belt-2 {
        background-position-y: 210px;
    }
    
    .container ul li#belt-3 {
        background-position-y: 123px;
        height: 58px;
    }
    
    .container ul li#belt-4 {
        background-position-y: 66px;
        height: 58px;
    }
    

    Always Remember all images in CSS sprites, should have same canvas size

    I create a basic example of CSS sprites, I hope this will help you.