Global solution for responsive images in Eleventy, allowing authors to use Markdown syntax for image and yet get responsive images in generated HTML.
« back to home | < back to step 5 |
In the folder of the tutorial step, run a clean install then build in developer mode:
npm ci
npm start
Sources are in src/
and build result is in dist/
.
If you open http://localhost:8080/
in a browser, nothing changed visualy and the page weight is the same.
However, if you check the source Markdown, it is simpler:
See how the logo “lost” its class and dimensions? There is no {.logo}{width=400}{height=400}
anymore.
We had these presets:
const presets = {
default: {
sizes: '(max-width: 45em) 90vw, 40em',
},
logo: {
sizes: '(max-width: 45em) 18vw, 8em',
},
};
We can use presets to add classes to images.
For example, we can add a logo
class to every image using the logo
preset with this syntax:
const presets = {
default: {
sizes: '(max-width: 45em) 90vw, 40em',
},
logo: {
sizes: '(max-width: 45em) 18vw, 8em',
classes: ['logo'],
},
};
We could also add multiple classes, as in Tailwind’s floated image:
const presets = {
default: {
sizes: '(max-width: 45em) 90vw, 40em',
},
logo: {
sizes: '(max-width: 45em) 18vw, 8em',
classes: ['float-right', 'ml-4', 'my-2', 'h-32'],
},
};
Please, don’t do this for production code, extract components… 🙏
We can also add other attributes to the images with the additional attributes
property in each preset.
For example, we can benefit from recent native lazy-loading in modern browsers with this:
const presets = {
default: {
sizes: '(max-width: 45em) 90vw, 40em',
attributes: {
loading: 'lazy',
},
},
logo: {
sizes: '(max-width: 45em) 18vw, 8em',
classes: ['logo'],
},
};
Note: The logo
preset will inherit the default
preset and override its common properties.
If logo pristine images always have the same dimensions, we could even add them to the logo
preset attributes:
const presets = {
default: {
sizes: '(max-width: 45em) 90vw, 40em',
attributes: {
loading: 'lazy',
},
},
logo: {
sizes: '(max-width: 45em) 18vw, 8em',
classes: ['logo'],
attributes: {
width: '400',
height: '400',
},
},
};
With this configuration, we can really reduce the authors work complexity, as we can see once again:
Note: If you use a DAM to manage high definition source images, you could make sure the site’s pristine images have always the same dimensions, 1600x1000
for example, and add them to the preset.
To be continued…