Home > Enterprise >  Why is the width of this element not 0?
Why is the width of this element not 0?

Time:10-21

I have a width set with a calc, and it should be returning 0 but when I look at the computed width it says 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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

it seems to me that the width of .test should be 0, especially as opacity is 0. If I make the value of the width property explicitly 0 it works.

CodePudding user response:

width accept length or percentage values and your calc() will return an integer.

It may look trivial for you because the result is 0 but it's not the case for the browser. calc(0) is not handled the same way as 0. The first one is invalid with width while the second is valid.

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

Add a unit to overcome this:

: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
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related