我在使用
<source>
元素时遇到的一个问题是,尽管在 width
和图像后备上提供了 height
和 <source>
属性,但仍然存在很大的布局变化,我认为这是因为我有提供了多个尺寸的图像(并且它们之间的尺寸存在很大差异)。 简化示例来说明:
<picture>
<source
sizes="(min-width: 900px) 900px, (min-width: 640px) 600px, (min-width: 340px) 300px, calc(100vw- 56px)"
srcset="/images/demo-300.avif 300w, /images/demo-600.avif, /images/demo-900.avif 900w"
type="image/avif" width="300" height="400" />
<source
sizes="(min-width: 900px) 900px, (min-width: 640px) 600px, (min-width: 340px) 300px, calc(100vw- 56px)"
srcset="/images/demo-300.webp 300w, /images/demo-600.webp 600w, /images/demo-900.webp 900w"
type="image/webp" width="300" height="400" />
<source
sizes="(min-width: 900px) 900px, (min-width: 640px) 600px, (min-width: 340px) 300px, calc(100vw- 56px)"
srcset="/images/demo-300.jpg 300w, /images/demo-600.jpg 600w, /images/demo-900.jpg 900w"
type="image/jpg" width="300" height="400" />
<img src="images/demo-300.jpg" width="300" height="400" />
</picture>
我希望这与提供图像的固有大小相同,因为
width
和 height
属性的值与 <img>
标签一起使用,以帮助浏览器正确为图像分配空间,渲染,即使您稍后使用 CSS 修改图像的大小。 <source>
标签,我想知道是否有任何解决方法。
这里遇到的错误是,尽管为源和图像提供了宽度和高度属性,但仍然观察到布局变化,特别是在加载不同尺寸的图像时。为了确保它不会发生,我们将把 包裹在具有相同比例的 a 中,然后添加所需的 css,如下所示:
<style>
.container {
position: relative;
width: 100%;
}
.aspect-ratio-placeholder {
width: 100%;
padding-top: calc(400 / 300 * 100%);
}
.image {
position: absolute;
top: 0;
<!-- begin snippet: js hide: false console: true babel: false -->
left: 0;
width: 100%;
height: 100%;
}
</style>
<div class="container">
<div class="aspect-ratio-placeholder"></div>
<picture class="image">
<source
sizes="(min-width: 900px) 900px,
(min-width: 640px) 600px,
(min-width: 340px) 300px,
calc(100vw - 56px)"
srcset="/images/demo-300.avif 300w,
/images/demo-600.avif,
/images/demo-900.avif 900w"
type="image/avif"
width="300"
height="400"
/>
<source
sizes="(min-width: 900px) 900px,
(min-width: 640px) 600px,
(min-width: 340px) 300px,
calc(100vw - 56px)"
srcset="/images/demo-300.webp 300w,
/images/demo-600.webp 600w,
/images/demo-900.webp 900w"
type="image/webp"
width="300"
height="400"
/>
<source
sizes="(min-width: 900px) 900px,
(min-width: 640px) 600px,
(min-width: 340px) 300px,
calc(100vw - 56px)"
srcset="/images/demo-300.jpg 300w,
/images/demo-600.jpg 600w,
/images/demo-900.jpg 900w"
type="image/jpg"
width="300"
height="400"
/>
<img src="images/vila-demo-300.jpg" width="300" height="400" />
</picture>
</div>