使用 CSS 网格布局时,我在 Safari 中遇到背景大小计算问题。我有一个网格容器,其中使用背景图像设置了背景图像,并且我尝试使用背景大小来调整其大小,并根据视口大小以及网格列数和行数进行计算。
这是我的代码的简化版本:
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>
矩形.svg:
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" style="border: 1px solid black">
</svg>
在大多数浏览器中,包括 Chrome 和 Firefox,背景大小计算似乎按预期工作。但是,在 Safari 中,背景图像出现扭曲或未正确覆盖网格容器。
我尝试过调整计算,尝试不同的单位,并检查 Safari 渲染背景大小的任何已知问题,但尚未找到解决方案。
浏览器版本:Safari 17
预期行为: 背景图像应覆盖网格容器而不失真,每个重复图像片段的大小根据视口大小和网格布局计算。
实际行为: 在 Safari 中,背景图像出现扭曲或未正确覆盖网格容器。
任何有关如何解决此问题的见解或建议将不胜感激。谢谢!
看起来你可以使用
repeating-linear-gradient
来代替 SVG 来制作网格线。这解决了 Safari 中的错位问题。它仍然不如 Chrome 光滑,但看起来并不破碎。
body {
margin: 0;
padding: 0;
}
.grid-container {
width: 100vw;
height: 100vh;
display: grid;
background-attachment: fixed;
grid-template-columns: repeat(22, minmax(0, 1fr));
grid-template-rows: repeat(12, minmax(0, 1fr));
background: repeating-linear-gradient(
to right,
#000000,
#000000 1px,
transparent 1px,
transparent calc((100 / 22) * 1vw)
),
repeating-linear-gradient(
to bottom,
#000000,
#000000 1px,
transparent 1px,
transparent calc((100 / 12) * 1vh)
);
}
.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);
}
<div class="grid-container">
<!-- Grid items here -->
<div class="child-1"></div>
<div class="child-2"></div>
<div class="child-3"></div>
<div class="child-4"></div>
<div class="child-5"></div>
<div class="child-6"></div>
<div class="child-7"></div>
<div class="child-8"></div>
<div class="child-9"></div>
</div>