Search code examples
csssvgfirefoxsafaricss-calc

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


Trying to use calc() with the stroke-dashoffset property in Safari (v12+) and Firefox (v84+) results in the browser rendering the value as 0px instead of the expected value. Chrome behaves as expected.

In the example below, both SVGs should look identical, with the line's stroke extending halfway across the square.

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>

Is this a bug with Safari and Firefox? Caniuse shows that both should fully support calc(). Is there another way to effectively use calc() in this situation?


Solution

  • You need to use units if you want to use calc in CSS, per this resolution

    Fortunately calc with units works on Chrome, Firefox and 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>