Frontendplace Blog

Sharing Frontend developing ideas

Sass Mixin for background image with retina support

Posted by info on September 12th, 2012

Here is an example for a sass stylesheet. to support Retina display images. This example only support .png images where the basename of the image is passed to the mixin as variable.

@mixin retina {
  @media (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 1.5dppx) {
    @content;
  }
}

@mixin generic-background-image($image) {
	background: image-url("#{$image}.png");
	  @include retina {
	    background: image-url("#{$image}@2X.png");
	}
}

h1 {
	@include generic-background-image("content");
}

This will generate:

h1 {
  background: url('../images/content.png');
}
@media (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3 / 2), (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 1.5dppx) {
  h1 {
    background: url('../images/content@2X.png');
  }
}