Prevent tablet and desktop showing mobile image when 1x, 2x, 3x pixel density has been applied for mobile

37 Views Asked by At

Based on my current code, mobile image will only display if the pixel density on a device is 1x (and below 576px viewport width).

When loading the site on an iPhone 12 (for example) even though the viewport size is below 576w, it's loading the desktop image.

Codpen: https://codepen.io/ChartersJ26/pen/rNqEqXB

<img src="{{ $column['mobile_image']['url'] }}"
    srcset="{{ $column['mobile_image']['url'] }} 576w,
        {{ $column['tablet_image']['url'] }} 992w,
        {{ $column['desktop_image']['url'] }} 1200w"
    sizes="(max-width: 576px) 576px,
    (max-width: 992px) 992px,
    1200px"
    alt="{{ $column['alt'] ?? '' }}"
    class="{{ $block }}__image">

My attempt to fix:

<img src="{{ $column['mobile_image']['url'] }}"
    srcset="{{ $column['mobile_image']['url'] }} 1x,
        {{ $column['mobile_image']['url'] }} 2x,
        {{ $column['mobile_image']['url'] }} 3x,
        {{ $column['tablet_image']['url'] }} 992w,
        {{ $column['desktop_image']['url'] }} 1200w"
    sizes="(max-width: 576px) 576px,
    (max-width: 992px) 992px,
    1200px"
    alt="{{ $column['alt'] ?? '' }}"
    class="{{ $block }}__image">

With this in place it works fine on mobile, but tablet and desktop are now always showing mobile image, so things have pretty much reversed.

If CSS or JS changes are required, that's fine just not sure best approach.

1

There are 1 best solutions below

0
Ujjawal Kumar On
<img src="{{ $column['mobile_image']['url'] }}"
    srcset="{{ $column['mobile_image']['url'] }} 576w,
        {{ $column['tablet_image']['url'] }} 992w,
        {{ $column['desktop_image']['url'] }} 1200w"
    sizes="(max-width: 576px) 100vw,
        (max-width: 992px) 50vw,
        33.33vw"
    alt="{{ $column['alt'] ?? '' }}"
    class="{{ $block }}__image">