The iPhone 4 and 4S have had high resolution retina screens for a while but now that the new iPad has been announced with an incredible 2047×1536 resolution retina images are going to be increasingly important for web sites and web apps.
I’ve created a small extension for Compass/SASS that makes using retina images much easier to manage.Firstly, its probably worth noting that the ideal solution for web images moving forward is going to be vector based. As screen screen resolutions get higher, so will the size of bitmap images. I still however think we’re a couple of years away from being able to wholesale switch to vector images, so in the mean time here is some code that will help make your life easier.
You can download the code and read the docs on how to install from GitHub.
What does it do?
For anyone who has used XCode to create an iOS app will know, images prefixed with a @2x
will be used as a replacement for standard artwork when run on a retina display. As an example, if you had an icon named icon-home.png
you could simple add icon-home@2x.png
to your project and the later image would be used on retina screens instead.
The important thing is to make sure that the @2x
images are twice the dimensions of the normal image.
This is a very simple solution and I wanted something similar for web apps I was working on. So I wrote a couple of custom Ruby functions and a couple of mixins and now a similar workflow can be achieved using Compass.
Using the extension you would call the following mixin:
.icon {
@include background-image-retina('icon-html.png');
}
This would first output the following CSS:
.icon {
background-image: 'image_dir/icon-html.png';
}
And then if an @2x
was found it would also output:
@media only screen and (-webkit-min-device-pixel-ratio: 2)
{
.icon {
background-size: 50% auto;
background-image: 'image_dir/icon-html@2x.png';
}
}
If no @2x
image is found, the retina CSS isn’t included but the Compass runtime won’t throw an error.
I’ve also included another helper function, which does the same but creates inline data URI’s instead:
@include inline-background-image-retina('icon-html.png');
I hope this is useful to a few others, I’d love to hear any feedback or feel free to raise a pull request if you find bugs or make improvements.