为什么这个元素的宽度不为0?

Why is the width of this element not 0?

我用计算器设置了宽度,它应该返回 0,但当我查看计算出的宽度时,它显示为 22.2333px。

:root {
  --show: 1;
}

.test {
  display: inline-block;
  overflow: hidden;
  width: calc(var(--show) - 1);
  opacity: calc(var(--show) - 1);
}
<span class="test">test</span>
<span class="test2">
      test2
    </span>

在我看来,.test 的宽度应该为 0,尤其是当不透明度为 0 时。如果我将宽度 属性 的值明确设为 0,它就可以工作。

width 接受长度或百分比值,您的 calc() 将 return 为整数。

它对您来说可能看起来微不足道,因为结果是 0 但对于浏览器而言并非如此。 calc(0) 的处理方式与 0 不同。第一个无效 width 而第二个有效。

A math function can be many possible types, such as <length>, <number>, etc., depending on the calculations it contains, as defined below. It can be used anywhere a value of that type is allowed. ref

添加一个单元来解决这个问题:

:root {
  --show: 1;
}

.test {
  display: inline-block;
  overflow: hidden;
  width: calc((var(--show) - 1)*1px);
  opacity: calc(var(--show) - 1);
}
<span class="test">test</span>
<span class="test2">test2</span>

相关: