treehouse : what would you like to learn today?
Web Design Web Development iOS Development

CSS Sprite with IMG tag and transparent method

  • I am using CSS Sprites but at a certain place I felt the need for img tag with a 1px transparent dot.

    So the code is -
    <img src="transparent.png" width="1" height="1" class="sprite">
    and css is
    .sprite{
    background: url(spriteImage.png) no-repeat -20px top;
    }

    Is this the correct alternate method to use CSS Sprite or it defiles the logic of reducing HTTP requests?
  • It would require an additional request if you do it like that. In the header, your CSS file will be loaded and any javascript, etc. If you use inline styling, it would require an additional request to render that image instead of already having it loaded through your stylesheet.
  • Even if an additional request is created, it should be fast because I am fetching only a 1px by 1px image and that too at may places.

    So is it worth the time?

    PS: @ChristopherBurton thanks for quick response
  • You're right, it will be a quick render for that small of an image. May I ask what the image is to be exact?
  • @ChristopherBurton social media icons in indented list.
  • can you post the image?
  • I'm not certain what you are trying to do, but it sounds as though you should just be using CSS padding.
  • @abhishek: If you are using a 1x1 pixel image, you could just convert it into a data URI. Then you don't have a HTTP request to worry about. It'll look similar to this:
    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
    9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
    The only problem is there is no way to cache it (I think) and you will have to repeat this format every time you need the same image.

    I got the above img tag example from wikipedia but you can use an online converter to make your own URI string. Please note that larger images make for much larger URI strings!

    Edit: Now that I think about it, a better method for you would be to use one of the other images that you are already using on the page and just clip it. That is if that image has a transparent area. So assuming the top left corner of your image is transparent, your code would look something like this:

    HTML
    <img src="already-used-image.png" class="tinyclip">
    CSS
    .tinyclip {
    clip:rect(0 1px 1px 0);
    }
    Here is a post that Chris made about it with more detail.