简答
将图像的原生宽度和高度(以像素为单位)作为属性添加到图像上。这让浏览器可以计算图像的纵横比。
<img width="600" height="400" src="some-image.webp"/>
长答案
width: 100% 没有给元素一个明确的宽度。
它所做的是定义相对于它的父容器的宽度。
height:auto 也没有给图像一个明确的高度,您是在指示浏览器根据图像比例或容器的大小使图像高度达到它认为合适的高度。
最大的问题是图像的高度(虽然 100% 的宽度并不明确,但纯粹从 CSS 计算实际宽度很容易)。
当页面被请求时,浏览器在开始下载之前不知道图像的比例。
由于这个原因,页面呈现(假设您有 inlined your critical CSS) 然后它会请求图像并找出图像的高度。图像的容器随后将更改大小以容纳此图像,您将获得布局转变,贡献给cumulative layout shift。
如何解决
选项 1 - 使用属性定义宽度和高度
选项一是使用属性将图像的高度和宽度定义为表示像素的整数:
<img width="600" height="400" src="some-image.webp"/>
在现代浏览器中,这将用于计算图像的纵横比,然后在图像开始下载之前在页面上分配足够的空间。
然后您可以像现在一样使用width:100%; height: auto;,它会按预期工作。
Using width and height attributes is the recommended best practice.
请注意 - 如果您使用 CSS 覆盖尺寸,则宽度和高度值必须是正确的纵横比(因此 width=200 height=100 将给出与 width=400 height=200 相同的结果,假设您在 CSS 中设置宽度)。
选项 2 - 使用“纵横比框”
在这种技术中,您将图像高度定义为 CSS 中宽度的比例。
本质上,我们将图像的高度设为零,然后使用填充来分配正确的空间量。
.image-div {
overflow: hidden;
height: 0;
padding-top: 56.25%; /*aspect ratio of 16:9 is 100% width and 56.25% height*/
background: url(/images-one.webp);
}
如果你不需要support Internet Explorer (as it is a little temperamental) you can use calc()。
padding-top: calc(900 / 1600 * 100%);
这个padding technique is explained in detail in this article from css-tricks。
虽然这有点小技巧,但优点是图像上没有内联属性,因此对于喜欢保持 HTML 干净的人很有用(并且对于某些情况,例如,如果您想让所有图像都相同)纵横比)
两者都有问题
这两种技术只有一个问题,您需要在渲染之前知道图像的宽度和高度,以便计算纵横比。
除非您愿意为图片制作一个固定高度和宽度的容器,否则您无能为力。
然后,如果图像与容器的纵横比不同,则图像周围会有一些空白区域,但页面不会发生布局变化(在大多数情况下会更可取)-假设您使用 overflow:hidden 等. 在容器上。
.container{
width:50vw;
height:28.125vw; /*fixed height, doesn't have to be aspect ratio correct, see example 2 */
overflow:hidden;
margin: 20px;
}
.container2{
width:50vw;
height:40vw; /*fixed height, but this time there is extra white space (shown as dark grey for the example) below the image.*/
overflow:hidden;
background: #333;
margin: 20px;
}
img{
width: 100%;
height: auto;
}
<div class="container">
<img src="https://placehold.it/1600x900"/>
</div>
<div class="container2">
<img src="https://placehold.it/1600x900"/>
</div>