Bright lights shining upwards obscures the stars...

Previous Entry Add to Memories Share Next Entry
CSS Spriting Tricks
Jeff with Leif and Piano
jbailey
For a project I'm having fun with, I have a tilemap that I want to use for sprites. Each tile is cleanly 16px by 16px.

Searching on the Interwebs, most people recommend making a background image and then using background-position in CSS to shift which image is being viewed.

There are a couple drawbacks to this:

1) You now have to put *something* in the element in order to make sure that it still exists on the page. So what usually happens here is a 10000px text-indent so that there's no chance that it will appear in the viewport.

2) You now have no option of scaling the image at all.

It turns out for option #2, there's some sort of magic scaling going into CSS3 called background-size, but it's not clear to me that it allow arbitrary aspect ratio changes.

I thought about it and came up with the following solution that seems to work well enough for me:

<!DOCTYPE html> <html> <head> <style> .wh-mapelement-image { position: absolute; } .wh-mapelement-container { position: absolute; height: 16px; width: 16px; overflow: hidden; display: block; } </style> </head> <body> <div class="element-container"> <img src="foo.png" class="element-image" width="640" height"432"> </div> </body> </html>
A .wh-mapelement-container:hover can be added here with left:-16px top:-16px to give the rollover effect to the sprite.

But wait! THAT'S NOT ALL!

If I double the width and the height on the image link, I can also double the width and the height in the container. That way, the browser's image size manipulations will work as expected and I can see my 16x16 pixel sprite on this reasonable DPI screen.

Hey Jeff!

Steve is working on a sprite editor for his brick engine game
I bet he would have things to say about this!

I, unfortunately, do not.
Nevertheless, glad you're having fun and figuring it out!

Mazarine

You are viewing jbailey