Skip to content

Instantly share code, notes, and snippets.

@btholt
Last active December 26, 2015 22:29
Show Gist options
  • Save btholt/7223380 to your computer and use it in GitHub Desktop.
Save btholt/7223380 to your computer and use it in GitHub Desktop.
/*
To make responsive images easy.
Sample use:
<style>
.responsive-image {
width: 100%;
height: 0px;
padding-bottom: 100%;
}
</style>
<div data-r-image="{{ my_image.url }}" class="responsive-image></div>
Intended for use with a framework like django with a CDN where you don't know where your images
are coming from until runtime. Instead of either running your static assets (like your CSS) through
your server or inlining your style for background images, this snippet of jQuery runs through and
takes them from a data tag and makes it the background.
Background-size and background-repeat are included for convenience. You can just as easily include
in the css like so:
[data-r-image] {
background-size: 100%, 100%;
background-repeat: no-repeat;
}
Advantage: Clean, clean code. All the inline styles get hellacious otherwise.
Disadvantage: No JavaScript? No images. :(
Author: Brian Holt
Twitter: @holtbt
Credit: Russell Ahlstrom (@janiv2) for correcting my assumptions.
*/
(function($) {
$('[data-r-image]').each(function() {
var $this = $(this);
$this.css({
'background-image': 'url(' + $this.data('rImage') + ')',
'background-size': '100%, 100%',
'background-repeat': 'no-repeat'
});
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment