仅将 CSS 样式应用于从 `<picture>` 元素加载的图像

Apply CSS style only to the loaded image from`<picture>` element

灯塔建议 using next-gen image formats for faster download and less data consumption。这是使用 HTML <picture> 元素完成的。

那么当我们使用 <picture> 元素时,如何将 CSS 样式仅定位到加载的图像?

在下面的代码片段中,您可以看到边框也被添加到其他元素。

picture * {
  border: 2px solid red;
}
<div style=" display: flex; gap: 30px; ">
  <p>AVIF: 50</p>
  <p>WebP: 100</p>
  <p>img: 150</p>
</div>

<picture>
  <source type="image/avif" srcSet="https://via.placeholder.com/50" width="50" height="50" />
  <source type="image/webp" srcSet="https://via.placeholder.com/100" width="100" height="100" />
  <img src="https://via.placeholder.com/150">
</picture>

注意:在撰写本文时,Chrome 支持 AVIF,Edge 和 Firefox 支持 WebP,因此会根据您的浏览器加载相应的文件类型。

Screenshot of above snippet result taken from Microsoft Edge for reference:

样式选择器只需要定位图片元素内的img标签即可。除了 picture * 你可以尝试做 picture img.

但是,建议将 class 添加到图片元素内的 img 标签,并在您的 CSS 中定位它以获得最佳实践。

加载的图像将由 img 标记表示,因此您可以只定位该元素。

不同的源元素只是提供不同的源(因此这样称呼)但浏览器决定使用什么(通过不同的因素)并将其加载到 img 标签中。

您可以通过标签名称 (picture img) 对其进行定位或添加实际的 css class(我会像 picture .image 那样推荐 - 请参阅代码段) .

picture .image {
  border: 2px solid red;
}
<div style=" display: flex; gap: 30px; ">
  <p>AVIF: 50</p>
  <p>WebP: 100</p>
  <p>img: 150</p>
</div>

<picture>
  <source type="image/avif" srcSet="https://via.placeholder.com/50" width="50" height="50" />
  <source type="image/webp" srcSet="https://via.placeholder.com/100" width="100" height="100" />
  <img class="image" src="https://via.placeholder.com/150">
</picture>