Dec. 22, 2022 · 2 min read
In HTML we can display several different image sizes depending on the size of the screen, thus allowing our website to be responsive.
The code would be the following:
<picture>
<source media="(min-width:650px)" srcset="img_pink_flowers.jpg">
<source media="(min-width:465px)" srcset="img_white_flower.jpg">
<img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>
Where through the source tag we establish the different conditions of the size of the screen, and depending on that size, one image or another is displayed. In Wagtail, we wanted to replicate this same behavior, and consulting the documentation, they offer us this solution:
<picture>
{% image page.photo width-800 as wide_photo %}
<source srcset="{{ wide_photo.url }}" media="(min-width: 800px)">
{% image page.photo width-400 %}
</picture>
Testing the documentation example, we saw that it was not working, there was no responsive for the images. To check why it wasn't working, we decided to compare the generated HTML for both examples, to see if there was anything suspicious there that would make us see the error.
And indeed, checking the generated HTML for the HTML example and for the Wagtail documentation example:
Example HTML: <img [...] src="original.jpg">
Example Wagtail: <img [...] src="original.jpg" width="480" height="320">
At first glance, we can already see the difference, the HTML code generated through the Django template tags has the width and height attributes with predefined values. By already having these values, it makes the re-size of the images through the specified source not work. Finally, the proposed solution for the re-size of images in Wagtail is the following:
{% image card_item.img fill-640x450-c50 as icon %}
{% image card_item.img fill-220x150-c50 as iconmobile %}
<picture>
<source media="(min-width:640px)" srcset="{{ icon.url }}">
<img loading="lazy" class="card-img" src="{{ iconmobile.url }}" alt="{{card_item.img.title}}">
</picture>
Declaring the two different images before the
We have opened a PR in the Wagtail repository advising that the example in the documentation did not work and proposing the above solution. At the moment it is under review 😉