简体   繁体   中英

Srcset attribute not working as expected on mobile and in mobile device view in Chrome dev tools

Given the following:

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<img
  src="https://www.bennet.org/blog/responsive-images-busy-people/images/curiosity-medium.jpg"
  alt="Mars Curiosity Rover takes an excellent selfie."
  srcset="
    https://www.bennet.org/blog/responsive-images-busy-people/images/curiosity-large.jpg 1120w,
    https://www.bennet.org/blog/responsive-images-busy-people/images/curiosity-medium.jpg 720w,
    https://www.bennet.org/blog/responsive-images-busy-people/images/curiosity-small.jpg 400w"
  sizes="(max-width: 400px) 400px, (max-width: 720px) 720px, (max-width: 1120px) 1120px"
>
</body>
</html>

I'd expect the image chosen by the browser to be small, medium then large when viewed on devices with viewport widths 400px, 720px and 1120px respectively. This is indeed the behaviour when testing in a desktop browser (dragging the window, refreshing the page), however this isn't the case when viewing the page with a real mobile device (iOS 14+). I have also tested this using Chrome DevTools in the device toolbar. Instead, the largest image is loaded in all cases. I checked the viewport width in the console, pictured in the image below.

Image when viewed on mobile device and when using Chrome DevTools device toolbar.

在移动设备上查看时以及使用 Chrome DevTools 设备工具栏时的图像。

Image when viewed in Chrome on desktop, simply resizing the window.

在桌面版 Chrome 中查看时的图像,只需调整窗口大小即可。

Is my understanding of srcset wrong? Could there be some issue elsewhere?

You need to be wary of the pixel density ratio. Iphones have a retina display with a 2x pixel density ratio (so a 1200px image is used for a 600px width).

Checkout How to use srcset and sizes for responsive images

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM