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

问题描述

在 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 中使用 calc,你需要使用单位,每 this resolution

幸运的是,带有单位的 calc 适用于 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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...