Skip to content

Instantly share code, notes, and snippets.

@melanierichards
Last active October 17, 2020 22:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melanierichards/22f1416047e2189d3f659aef3e810342 to your computer and use it in GitHub Desktop.
Save melanierichards/22f1416047e2189d3f659aef3e810342 to your computer and use it in GitHub Desktop.
Eleventy Markdown shortcode I use for responsive images
// Shortcode for responsive images in blog posts
eleventyConfig.addShortcode("responsiveImage", function(baseSrc, ext, max, alt, classes) {
let fullBaseSrc = '/assets/images/content/' + baseSrc;
var sources = '<source media="(min-width: 501px)" srcset="' + fullBaseSrc + '-m.' + ext + '">';
if (max !== 'm') {
sources = '<source media="(min-width: 801px)" srcset="' + fullBaseSrc + '-l.' + ext + '">' + sources;
}
if (max === 'xl') {
sources = '<source media="(min-width: 1201px)" srcset="' + fullBaseSrc + '-xl.' + ext + '">' + sources;
}
return `<div class="c-media ${classes}"><picture>${sources}<img src="${fullBaseSrc}-s.${ext}" alt="${alt}" /></picture></div>`;
});
/*
EMBED LIKE THIS (third attribute is max size "m", "l" or "xl"):
{% responsiveImage "baseImageSrcWithoutExtOrSize", "jpg", "xl", "Alt text", "your-classes space-separated" %}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment