Search code examples
csscss-spritesbackground-position

Using Css Sprites and background position


I have a div element, say of width 200px and height 200px. I need a small image to appear on the top right corner of the div. How one would normally do it would be with

background: url(/images/imagepath.png) top right;

However the problem is, I am loading the image from a sprite and when I use something like

background: url(/web/images/imagepath.png) -215px -759px  top right;

the sprite doesnt seem to pick it from the right location. Some other part of the sprite is loaded. Is it possible to load an image from sprite and use the background-position attribute as well. Thanks in advance...


Solution

  • You need to specify the coordinates for your element position and the background position in two different ways.

    #yourimage {
      background-image: url(/web/images/imagepath.png);
      /* background coordinates */
      background-position: -215px -759px;
    
      /* element coordinates */
      position:absolute;
      left: 0;  /* 0px from the left */
      top:  0;  /* 0px from the top  */
    }
    

    With the background-position you specify the background coordinates. For the coordinates of your element, you need to set the left and right properties.

    Keep in mind that in order to use sprites, your element must be of the correct size. The image you are using as a background must have enough space to cover the width and height of the element, not more, otherwise you will see more than one image from your sprites image.

    If you want to display a image smaller than your element, you need a smaller element inside the big one.

    <div id="container">
      <div class="background"></div>
      my content here
    </div>
    

    Then in your CSS

    #container {
      position:relative;
      width: 200px;  /* size of your big element */
      height: 200px;
    }
    #container .background {
      background: url(/web/images/imagepath.png) -215px -759px;
      width:  50px; /* width and height of the sprite image you want to display */
      height: 50px;
      position: absolute;
      top: 0;
      left: 0;
    }