处理不同尺寸的延迟加载图像的纵横比,以避免内容跳转



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

但是,只有当所有图像都在同一维度上时,此解决方案才能完美运行。

渲染不同维度图像时如何处理内容跳转?

仅供参考:对于延迟加载图像,我使用的是延迟大小

.wrapper {
position: relative;
height: 0;
padding-top: calc(100 / 411 * 100%);
}
.wrapper_img {
position: absolute;
top: 0;
left: 0;
max-width: 100%;
height: auto;
}
<!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>

这是JSBin的链接。

@sravis 您是否在处理一组有限的纵横比?如果是这样,那么您可以为每个纵横比使用不同的类。如果没有,则预先设置imgheightwidth可以防止内容重排。

由于您没有一组纵横比,因此如果呈现 html,您将需要图像大小(或纵横比)。 指定图像宽度/高度属性很好,但不能解决您的问题。

你可以做什么

  • 一个想法是使用填充顶部的实现将包装器div 作为内联样式提供纵横比。

  • 另一个想法是使用带有自定义 css 变量的内联样式,因为这些变量被广泛支持。看看片段。这是一个示例,它具有带有边框的固定包装宽度并放大图像。

无论您决定使用什么

  • 注意损坏的图像,这可能会破坏您的纵横比。
  • 太小而无法填充整个包装器的图像在布局中看起来会有点迷失。要么使用对象拟合和对象定位来解决这个问题 - 要么只是省略代码片段中的max-widh以扩大它们。

/* css for wrapper only for demonstration purposes and not really needed */
.wrapper {
width: 300px; /* just to limit the size */
border: 1px solid black;
box-sizing: border-box;
}
/* tricky stuff starts here */
[style*="--aspect-ratio"] {
position: relative;
}
[style*="--aspect-ratio"]::before {
content: "";
display: block;
padding-bottom: calc(100% / (var(--aspect-ratio)));
}
[style*="--aspect-ratio"] > img {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
<!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" style="--aspect-ratio:411/100">
<img class="wrapper_img" src="https://placehold.it/411x100" />
</div>
</div>
Test 002 (broken by intention)
<div>
<div class="wrapper" style="--aspect-ratio:150/100">
<img class="wrapper_img" src="https://broken-placehold.it/150x100" />
</div>
</div>
Test 003
<div>
<div class="wrapper" style="--aspect-ratio:411/600">
<img class="wrapper_img" src="https://placehold.it/411x600" />
</div>
</div>
Test 004
<div>
<div class="wrapper" style="--aspect-ratio:150/100">
<img class="wrapper_img" src="https://placehold.it/150x100" />
</div>
</div>
</div>
</body>
</html>

我遇到了同样的问题。我解决了从文件(php)获取图像大小的问题:

$data = getimagesize("path/to/file");

计算纵横比:

$aspectratio = $data[0]/$data[1];

将其设置为父div 的 CSS 样式:

<div class="portfolio-wrap" style="aspect-ratio: '.round($aspectratio,1).';">
<img/>
</div>

最新更新