Skip to content

Instantly share code, notes, and snippets.

@erin-dot-io
Created September 28, 2012 19:10
Show Gist options
  • Save erin-dot-io/3801596 to your computer and use it in GitHub Desktop.
Save erin-dot-io/3801596 to your computer and use it in GitHub Desktop.
Sass/SCSS Mixin for Providing Simple HI-DPI/Retina Display Media Queries for Background Images
// SCSS:
$image-path: "/assets/images";
@mixin background-hidpi($image-name, $image-extension: "png", $top: top, $left: left, $repeat: repeat, $color: #fff) {
background: url("#{$image-path}/#{$image-name}.#{$image-extension}") $top $left $repeat $color;
@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) {
background: url("#{$image-path}/#{$image-name}_2x.#{$image-extension}") $top $left $repeat $color;
}
}
body {
@include background-hidpi(textures/stripes, jpg);
}
// RESULTING CSS:
body {
background: url("/assets/images/textures/stripes.jpg") top left repeat white;
@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) {
body {
background: url("/assets/images/textures/stripes_2x.jpg") top left repeat white; } }
@erin-dot-io
Copy link
Author

NOTICE: This is an initial version, use at your own risk! Would love to hear ideas and/or suggestions for improvements.

As I was looking around the web for a simple SASS/SCSS solution to writing media queries for hi-dpi image assets, I found a few nice resources but nothing that fit my exact needs, so I threw this little guy together:


Simply throw your assets into your project's images folder, providing two versions: one with a normal name (stripes.jpg), and another (hopefully 200% in size) with _2x appended to the name, right before the extension (stripes_2x.jpg).

Next set the variable $image-path to your project's images folder (e.g. /assets/images):

$image-path: "/assets/images";

The mixin will prepend your file with this path, and any additional sub-directories can be added by including them in the @include itsself:

@include background-hidpi(textures/stripes);

...will result in:

"/assets/images/textures/stripes.png"

and

"/assets/images/textures/stripes_2x.png"

respectively.

Also, the mixin defaults to a .png file extension, but this can be overridden by adding a specific extension (like .jpg).

You can also override the default positioning properties in the @include or you can change them directly in the mixin.

@include background-hidpi(stripes, jpg, -10px, 20px, #666);

The only variable that has to be declared in the @include is the image file name (excluding the _2x and the extension so long as its .png).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment