Calc() 不适用于 Safari 和 Firefox 中的 stroke-dashoffset

Calc() not working with stroke-dashoffset in Safari and Firefox

尝试在 Safari (v12+) 和 Firefox (v84+) 中将 calc()stroke-dashoffset 属性 一起使用会导致浏览器将值呈现为 0px 而不是期望值。 Chrome 表现符合预期。

在下面的例子中,两个 SVG 看起来应该是一样的,线条的笔划延伸到正方形的一半。

svg {
  border: 1px solid red;
}
.withCalc line,
.withoutCalc line {
  stroke-dasharray: 190;
}
.withCalc line {
  stroke-dashoffset: calc(190 / 2);
}
.withoutCalc line {
  stroke-dashoffset: 95;
}
<svg class="withCalc" viewBox="0 0 200 200" width="200" height="200">
  <line x1="5" y1="100" x2="195" y2="100" stroke="black"/>
</svg>
<svg class="withoutCalc" viewBox="0 0 200 200" width="200" height="200">
  <line x1="5" y1="100" x2="195" y2="100" stroke="black"/>
</svg>

这是 Safari 和 Firefox 的错误吗? Caniuse shows that both should fully support calc()。在这种情况下,还有其他有效使用 calc() 的方法吗?

如果您想在 CSS 中使用计算器,您需要使用单位,根据 this resolution

幸运的是,带单位的计算适用于 Chrome、Firefox 和 Safari。

svg {
  border: 1px solid red;
}
.withCalc line,
.withoutCalc line {
  stroke-dasharray: 190px;
}
.withCalc line {
  stroke-dashoffset: calc(190px / 2);
}
.withoutCalc line {
  stroke-dashoffset: 95px;
}
<svg class="withCalc" viewBox="0 0 200 200" width="200" height="200">
  <line x1="5" y1="100" x2="195" y2="100" stroke="black"/>
</svg>
<svg class="withoutCalc" viewBox="0 0 200 200" width="200" height="200">
  <line x1="5" y1="100" x2="195" y2="100" stroke="black"/>
</svg>