skip to Main Content

The code shows 0 and 1, and why does it shows 2 sometimes?

My browser is Microsoft Edge v130, and Chrome v130 does the same.

@property --vw {
  syntax: "<length>";
  inherits: true;
  initial-value: 100vw;
}
:root {
  --w: mod(tan(atan2(var(--vw), 1px)), 2);
}
body::before {
  counter-reset: w var(--w);
  content: counter(w);
}
<body></body>

2

Answers


  1. The reason your code sometimes shows 2 instead of 0 or 1 is due to floating-point numbers.
    You can try using min

        :root {
      --w: min(mod(tan(atan2(var(--vw), 1px)), 2), 1.9999);
    }
    
    Login or Signup to reply.
  2. When you use calc or another CSS function, it can be hard to see what the computed value is. If you do getComputedStyle(document).getPropertyValue("--w") you just get the formula, not the value.
    One trick to see what the computed value is, is to assign it to a real property. Since your --w property hasn’t got a unit, you could assign it to line-height.

    body {
      font-size: 1px;
      line-height: var(--w);
    }
    

    Now, you can see the value, which might for example be 1.99. The counter-reset property only takes integers and 2 is "close enough".

    You can use round() to round the number (up, down, nearest integer or to-zero):

    :root {
      --w: mod(round(nearest, tan(atan2(var(--vw), 1px)) ), 2);
    }
    

    (The round() can also go outside the mod(), whatever makes sense to you)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search