Last Updated: September 09, 2019
·
5.775K
· flexbox

Sass retina background mixin

Like me you are a front-end ninja and you follow the DRY principes. Here is a pretty cool mixin to generate a background image for retina display.

I Suppose you have already defined a variable $retina somewhere in your scss files.

$retina: "only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx)";

mixin

@mixin retina-background-image($file, $type, $width, $height) {
  background-image: url($file + '.' + $type);
  @media #{$retina} {
    background-image: url($file + '@2x.' + $type);
    @include background-size($width, $height);
  }
}

Usage

You just define the image path, the image type and eventually the background-size

@include retina-background-image("images/video", "png", 50%, 50%);

3 Responses
Add your response

Don’t use @2x in the filename, since the @ character in a URL is reserved as the delimiter separating the username and password from the host in authentication URL schemes.

https://developer.apple.com/library/safari/documentation/NetworkingInternet/Conceptual/SafariImageDeliveryBestPractices/ServingImagestoRetinaDisplays/ServingImagestoRetinaDisplays.html#//apple_ref/doc/uid/TP40012449-CH3-SW1

over 1 year ago ·

That make sense.
I use @2x because i think it was a naming convention like http://retinajs.com/

over 1 year ago ·

I've modified
@include background-size($width, $height);
to
background-size: $width $height;

over 1 year ago ·