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

Sea*_*ean 2 css safari firefox svg css-calc

尝试在 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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

这是 Safari 和 Firefox 的错误吗?Caniuse 表明双方都应该全力支持calc()。在这种情况下有没有其他方法可以有效地使用calc()

Rob*_*son 7

如果你想在CSS中使用计算,你需要使用单位,根据这个分辨率

幸运的是,带有单位的计算器可以在 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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)