0

What is the correct syntax to consume a css variable inline and calculate with that variable?

In the code below, there is a variable --value defined in the inner div. I want to consume that variable and use it to calculate a number. What is the correct syntax to do so?

export default function App() {
  const [val, setVal] = React.useState<number>(3);
  return (
    <div style={{
      position: "relative",
    }}>
      <h1>Consuming CSS variables</h1>
      <input 
        id="val" 
        name="val" 
        step={10}
        value={val} 
        onChange={e=>setVal(Number(e.target.value))} 
        type="number" />
      <div style={{
        display: "flex",
        "--value": val
      } as React.CSSProperties}>
        <div style={{
          display: "block",
          margin: "3rem 6rem",
          position: "absolute",
          left: 0,
          width: "50px",
          height: "50px",
          // transform: `scaleX(${100+val}%)`, // this works of course
          transform: `scaleX(calc(100+var(--value))%)`, // <-- how to make this work?
          backgroundColor: "red",
        }} ></div>
      </div>
    </div>
  );
}

Codesandbox: link

wongz
  • 3,255
  • 2
  • 28
  • 55

0 Answers0