When uploading an image via the cms, multiple versions should be generated using defined ratios and sizes.
To use a specific image source in the frontend, a key like 2_1_1920
is used, which would in this case deliver a version of the image with a ratio of 2:1
and a width of 1920px
.
Here's an example of an image, that should keep the ratio 2:1 in all viewports.
Within the <picture>
element there are 4 <source>
elements and 1 <img>
element as fallback.
<picture>
<source srcset="2_1_1920, 2_1_3840 2x" media="(min-width: 1200px)"><!-- A -->
<source srcset="2_1_1200.jpg, 2_1_2400.jpg 2x" media="(min-width: 700px)"><!-- B -->
<source srcset="2_1_700.jpg, 2_1_1400.jpg 2x" media="(min-width: 340px)"><!-- C -->
<source srcset="2_1_340.jpg, 2_1_680.jpg 2x"><!-- D -->
<img srcset="2_1_340.jpg">
</picture>
With the 4 sources, we are addressing 4 different viewports:
(using the same order as the <source>
elements above)
<source> attribute |
description | |
---|---|---|
A | "min-width: 1200px" | 1200px screen width and beyond (larger desktops, mostly 1920 width / full hd) |
B | "min-width: 700px" | 700px-1199px (tablets and smaller desktops) |
C | "min-width: 340px" | 340px-699px (phones in landscape) |
D | "(no min-width)" | 0-339px (phones in portrait) |
Every <source>
element holds 2 image resources, one for normal displays, one for higher density / retina displays (marked with 2x
).
Both of images have the largest possible resolution for their respective viewport.
In this example, the min-width of the next larger viewport is used. Except for large desktops, where full hd resolution is used.
Using a ratio of 2:1, image source resolutions for this example would be as follows:
normal | retina | |
---|---|---|
A | 1920x960 | 3840x1920 |
B | 1200x600 | 2400x1200 |
C | 700x350 | 1400x700 |
D | 340x170 | 680x340 |
Browser support for this whole functionality is provided using picturefill, which contains a polyfill for the picture element with support for viewport dependent image sources.