ARTICLE AD BOX
In this example, I create a div element with 100% width. I then compute in two different means the position of the mouse in the div: left-most position should give value 0, while right-most position should give value 1 (ratio of offset to width).
I compute in javascript and that works as expected. I also compute with css, but I get a completely different result. There must be something I am missing about the css here.
Here is my code:
<html> <head> <style> @property --x-offset { syntax: '<number>'; inherits: true; initial-value: 0; } @property --cssVal { syntax: '<number>'; inherits: true; initial-value: 0; } body { margin: 0; padding: 0; } div { width: 100%; height: 100vh; --cssVal: calc(var(--x-offset) * 1px / 100%); } </style> </head> <body> <div></div> <script type="module"> const div = document.querySelector('div') div.addEventListener('mousemove', (evt) => { const width = window .getComputedStyle(div) .getPropertyValue('width') .slice(0, -2) const offset = evt.offsetX const jsVal = offset / width div.style.setProperty('--x-offset', `${offset}`) const cssVal = window.getComputedStyle(div).getPropertyValue('--cssVal') // expected to be equal, but are very different console.log(cssVal, jsVal) }) </script> </body> </html>Update:
With css, I do get 0 (as expected) for the left-most part; but for the right-most, the result is dependant on the window size (and in any case, is very different than 1, as I would expect).
Assumption: I am on Chrome, and assuming browser support for calc().
My question: why is the CSS computation not resulting in value 1?
