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
相关产品推荐
相关产品推荐

