You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Safari浏览器中figure元素aspect-ratio属性失效问题求助

Safari中CSS变量设置aspect-ratio失效问题修复

问题概述

使用aspect-ratio: var(--aspect-ratio)为figure元素设置宽高比时,Chrome和Firefox能正常基于max-width和max-height拉伸并保留宽高比,但Safari中元素会被拉伸且丢失宽高比,导致图片溢出容器。

示例代码

<style>
  figure {
    display: block;
    max-width: 10vw;
    max-height: 30vh;
    background: red;
    aspect-ratio: var(--aspect-ratio);
  }

  figure>img {
    opacity: 0.5;
    width: 100%;
    object-fit: contain !important;
  }
</style>

<figure style="--aspect-ratio: 2.3748810656518" class="img-container landscape">
  <img alt="Grand Horizontal" src="https://catherineviollet.fr/media/pages/projets/les-chemins-d-eau/14155ef03e-1714326097/grand-horizontal-2022-acrylique-pigments-fraisage-sur-papier-124x300-1500x.jpg" loading="lazy">
</figure>

<figure style="--aspect-ratio: 0.62680361946686;" class="img-container">
  <img alt="Gulf Stream" src="https://catherineviollet.fr/media/pages/projets/les-chemins-d-eau/29fdecc0af-1714326097/gulf-stream-2021-acrylique-pigments-fraisage-sur-papier-210x130-1500x.jpg">
</figure>

修复方案

方案1:用calc包裹CSS变量

Safari对直接在aspect-ratio中使用CSS变量的解析存在bug,通过calc()包裹变量可解决:

figure {
  display: block;
  max-width: 10vw;
  max-height: 30vh;
  background: red;
  aspect-ratio: calc(var(--aspect-ratio)); /* 关键修改 */
}

方案2:添加明确尺寸约束

给figure添加width: 100%和min-width: 0,帮助Safari正确计算宽高比:

figure {
  display: block;
  max-width: 10vw;
  max-height: 30vh;
  background: red;
  aspect-ratio: var(--aspect-ratio);
  width: 100%;
  min-width: 0; /* 确保容器能适配约束 */
}

方案3:传统padding-top模拟宽高比(兼容旧版Safari)

如果需要兼容更旧的Safari版本,可使用padding-top技巧模拟宽高比:

figure {
  display: block;
  max-width: 10vw;
  max-height: 30vh;
  background: red;
  position: relative;
  height: 0;
  padding-top: calc(100% / var(--aspect-ratio)); /* 用padding-top实现宽高比 */
}

figure>img {
  opacity: 0.5;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain !important;
}

内容的提问来源于stack exchange,提问作者Aurore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 23:18:10