Slightly easier retina ready images using SCSS

Jason Z posted a really useful Sass mixin for helping with retina-ready images. I added it to my helpers and changed a few things to make it easier for me to work with.

The example assumes you are using a PNG and the @2x naming convention for your 2x images. Update the ‘.png’ to whatever file extension you need. Height and width can be specified in the relative ‘em’ unit.

// Jason Z’s helper is added like this:
div.logo {
  background: url("logo.png") no-repeat;
  @include image-2x("logo2x.png", 100px, 25px);
}

// Mine goes like this:
div.logo {
  @include image-2x(logo, 100px, 25px);
}

// My modified helper, or mixin, looks like this:
@mixin image-2x($image, $width, $height) {
  background: url("#{$image}.png") no-repeat;
  
  @media (min--moz-device-pixel-ratio: 1.3),
         (-o-min-device-pixel-ratio: 2.6/2),
         (-webkit-min-device-pixel-ratio: 1.3),
         (min-device-pixel-ratio: 1.3),
         (min-resolution: 1.3dppx) {
    
    // on retina, use image that’s scaled by 2
    background-image: url("#{$image}@2x.png)");
    background-size: $width $height;
  }
}

The difference is that the first, non-retina, background image does not need to be declared separately, before the @include. It makes things easier to read if both images are declared, but I find the more concise version works better for me because I’ve tailored it to the conventions I work with.

Filenames, or CSS selectors can be concatenated, or stuck together, with Sass by using the #{$variable} syntax. So in this case only the image filename needs to be passed into the @include, without the file extension, then the ‘.png’ and ‘@2x.png’ get appended appropriately.

Trigger

I mentioned TextExpander among the tools I work with and for this—after about the fourth time searching my document to copy and reuse the @include code—I created a snippet so typing ‘@@image’, in my text editor, outputs ‘@include image-2x(image-name, width, weight);’. Which speeds things up an extra bit and gives my brain less to remember.

Paddy O’Hanlon is a web designer and one of the principals at Logo24. He is a lover of good semantics, well documented and architected CSS, and beautiful, content-driven design. (Really the design-guise is a cover-up so he can covertly feed his travel addiction and climb many rocks around the world). He tweets @Paddy.

Comments make us happy