Use retina images painless
Originally posted on Tumblr on
I hate blurry sites and graphics on High Res devices. I also hate to write all these CSS media queries for high resolution screen that takes time and is not fun.
So in the real world, without any help of this great masterpiece of modern web development called Sass our CSS code must be like this:
.not-cool {
width: 150px;
height: 40px;
background-image: url('not-cool.png');
}
@media (min--moz-device-pixel-ratio: 1.5),
(-o-min-device-pixel-ratio: 3/2),
(-webkit-min-device-pixel-ratio: 1.5),
(min-device-pixel-ratio: 1.5),
(min-resolution: 144dpi),
(min-resolution: 1.5dppx) {
.not-cool {
background-image: url('.not-cool@2x.png');
-webkit-background-size: 150px 40px;
-moz-background-size: 150px 40px;
-o-background-size: 150px 40px;
background-size: 150px 40px;
}
}
Not cool right? Just imagine writing all this code everytime you have to use a retina image!
Here comes my .cool solution!
I felt special when I first thought this great mixin that helps you write really fast and clean code with just one line! Just that difficult, but you can always improve it, I also dont know if there is any other same mixin out there but I still love mine <3
//First call your compass mixin to make your life easier.
@import "compass/css3/background-size";
//And then let's start our mixin
//I found the great name background-image-with-retina.
//You can make yours, like bg-retina or just retina.
//Its up to you!
@mixin background-image-with-retina( $img, $filetype, $size ) {
background-image: image-url( $img + '.' + $filetype );
@include background-size( $size );
@media (min--moz-device-pixel-ratio: 1.5),
(-o-min-device-pixel-ratio: 3/2),
(-webkit-min-device-pixel-ratio: 1.5),
(min-device-pixel-ratio: 1.5),
(min-resolution: 144dpi),
(min-resolution: 1.5dppx) {
& {
background-image: image-url($img + '@2x' + '.' + $filetype);
}
}
}
Try to read it and I will explain it. First we have 3 variables the $img, $filetype and the $size
- $img: is the name of the image without the extenstion e.g. cool
- $filetype: is the type of the image, only the extension e.g. png
- $size: is the size of the image in pixels that has to be applied with the background-size property e.g. 150px 40px
Then the mixin take care to join all these to one. You can make it smarter and more efficient but this is the basic idea and works really good!
So before you are ready to go live you have to call it, let’s see how our CSS should be know with the cool way:
.cool {
width: 150px;
height: 40px;
@include background-image-with-retina( 'cool', 'png', '150px 40px' );
}
Just this, not media queries, no double background images only 1 cool line :) Hope you enjoyed this post too and don’t forget to share the love!
