Handling aspect ratio of lazy loading images with different dimensions to avoid content jump

sra*_*vis 6 html css lazy-loading image

padding-top: calc(height / widht * 100%); I 的帮助下, 我可以处理延迟加载的图像以避免内容跳转。

但是,仅当所有图像都在同一尺寸上时,此解决方案才能完美工作。

渲染不同尺寸的图像时如何处理内容跳跃?

仅供参考:对于延迟加载图像,我正在使用lazysizes

.wrapper {
  position: relative;
  height: 0;
  padding-top: calc(100 / 411 * 100%);
}

.wrapper_img {
  position: absolute;
  top: 0;
  left: 0;
  max-width: 100%;
  height: auto;
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div>
    <p>Test 001</p>

    <div>
      <div class="wrapper">
        <img class="wrapper_img" src="https://placehold.it/411x100" />
      </div>
    </div>

    Test 002

    <div>
      <div class="wrapper">
        <img class="wrapper_img" src="https://placehold.it/150x100" />
      </div>
    </div>

    Test 003

    <div>
      <div class="wrapper">
        <img class="wrapper_img" src="https://placehold.it/411x600" />
      </div>
    </div>

    Test 004

  </div>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

是指向JSBin的链接。

小智 0

@sravis 你正在处理一组有限的长宽比吗?如果是这样,那么您可以为每个长宽比使用不同的类。如果没有,则预先设置img's,heightwidth可以防止内容回流。

  • 这意味着在图像标签而不是 CSS 中设置 H/W。所以 `&lt;img height="300" width="400" /&gt;` 如果你等待 CSS,你可能会导致重绘。您还可以考虑使用[本机延迟加载](https://web.dev/native-lazy-loading)解决方案。 (2认同)