Safari中CSS Grid布局下background-size计算失真问题求助
Safari 17中CSS Grid背景图background-size计算异常问题
问题概述
使用CSS Grid布局时,为网格容器设置基于视口尺寸和网格行列数计算的background-size,在Chrome、Firefox等浏览器中表现正常,但在Safari 17中背景图出现失真,无法正确覆盖网格容器。
简化代码
index.html
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Background Size Issue</title> <style> body { margin: 0; padding: 0; } .grid-container { width: 100vw; height: 100vh; display: grid; grid-template-columns: repeat(22, minmax(0, 1fr)); grid-template-rows: repeat(12, minmax(0, 1fr)); background-image: url('./rectangle.svg'); background-size: calc(100vw / 22) calc(100vh / 12); background-repeat: repeat; } .child-1 { grid-column: span 9 / span 9; background-color: rgba(255, 0, 0, 0.5); } .child-2 { grid-column: span 1 / span 1; background-color: rgba(134, 82, 48, 0.5); } .child-3 { grid-column: span 1 / span 1; background-color: rgba(48, 72, 134, 0.5); } .child-4 { grid-column: span 1 / span 1; background-color: rgba(134, 48, 48, 0.5); } .child-5 { grid-column: span 9 / span 9; background-color: rgba(0, 255, 0, 0.5); } .child-6 { grid-column: span 1 / span 1; background-color: rgba(251, 255, 0, 0.5); } </style> </head> <body> <div class="grid-container"> <!-- Grid items here --> </div> </body> </html>
rectangle.svg
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" style="border: 1px solid black"> </svg>
行为对比
- 预期行为:背景图无失真覆盖网格容器,每个重复片段尺寸匹配网格单元格大小
- 实际行为:Safari 17中背景图失真,无法与网格单元格对齐
效果截图


解决方案尝试
1. 改用容器百分比计算background-size
将基于视口的计算改为基于网格容器自身的百分比,避免Safari对视口单位与网格布局的计算冲突:
.grid-container { /* 其他属性不变 */ background-size: calc(100% / 22) calc(100% / 12); }
2. 使用CSS变量统一行列数定义
通过CSS变量管理网格行列数,让浏览器更稳定解析计算逻辑:
:root { --grid-col-count: 22; --grid-row-count: 12; } .grid-container { width: 100vw; height: 100vh; display: grid; grid-template-columns: repeat(var(--grid-col-count), minmax(0, 1fr)); grid-template-rows: repeat(var(--grid-row-count), minmax(0, 1fr)); background-image: url('./rectangle.svg'); background-size: calc(100% / var(--grid-col-count)) calc(100% / var(--grid-row-count)); background-repeat: repeat; }
3. 优化SVG的缩放行为
为SVG添加preserveAspectRatio="none",强制其按指定尺寸缩放,避免默认比例约束导致的失真:
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" preserveAspectRatio="none" style="border: 1px solid black"> </svg>
4. 利用网格单元格的内在尺寸
通过background-size: auto结合background-repeat: space,让浏览器自动匹配网格单元格尺寸,但需确保SVG原始宽高比与网格单元格比例一致:
.grid-container { /* 其他属性不变 */ background-size: auto; background-repeat: space; }
原理说明
Safari 17在处理calc()结合视口单位(vw/vh)与Grid布局的尺寸计算时,可能存在精度偏差或渲染优先级问题。改用容器百分比、CSS变量可以让浏览器更准确地关联网格容器的实际尺寸;优化SVG属性则避免了矢量图缩放时的默认比例限制,从而解决失真问题。
内容的提问来源于stack exchange,提问作者tawfikboujeh
相关产品推荐
相关产品推荐

