Home > Back-end >  get only the numeric value of CSS variable, without its type
get only the numeric value of CSS variable, without its type

Time:05-12

I want to make some calculation in CSS and use the result as a non-typed value.
This is what I've tried:

:root {
  --scale: 100vh / 1920;
}

canvas {
  height: 1920px;
  width: 1080px;
  transform: scale(var(--scale));
}

Nah, it didn't work, because --scale is some value in vh, like .8vh or 1.1vh, but I need it to be just a float, as .8 or 1.1.
Is there any way to use that variable without the type (vh), only with its numeric value? (I would prefer to do this with CSS only, without JS)
I need the initial values of height and width to be those, because I'll export the canvas as a png with that size, and scale does affect only the visualization, not the render of the canvas context.

Edit:
I've solved this with JS:

  const resize = () => {
    const ratio = (window.innerHeight) / 1920;
    // container is a div wrapping the canvas
    const containers = document.querySelectorAll('.container');
    containers.forEach(container => {
      const minMarginHeight = Math.min(0, (ratio - 1)/2 * container.clientHeight);
      const minMarginWidth = Math.min(0, (ratio - 1)/2 * container.clientWidth);
      container.style.transform = `scale(${ratio})`;
      container.style.margin = `${minMarginHeight}px ${minMarginWidth}px`;
    });
  }

  window.addEventListener('resize', () => {
    resize();
  });

but I was still looking for a pure CSS solution...

CodePudding user response:

You can use calc() in this case

canvas {
  height: 1920px;
  width: 1080px;
  transform: scale(calc(100/1920));
}

CodePudding user response:

You can wrap canvas element with some wrapper (.wrapper in Code snippet) and define CSS --scale variable in .wrapper to 100%. In case of % it can be calculated in calc function and you will get your scale size.

body {
  margin: 0;
}

.wrapper {
  height: 100vh;
  background: #673ab7;
  
  --scale: calc(100% / 2);
}

canvas {
  background: tomato;
  transform: scale(var(--scale, 1));
  height: 100%;
  aspect-ratio: 16/9;
}
<div >
  <canvas />
</div>

  • Related