Aug. 24th, 2009

jbailey: (Default)
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.

April 2010

S M T W T F S
    123
45678910
11121314151617
18192021222324
252627282930 

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 7th, 2025 11:58 pm
Powered by Dreamwidth Studios