Home > Enterprise >  Why can't I undo transform:scale() with the formula 1/a?
Why can't I undo transform:scale() with the formula 1/a?

Time:06-08

I am trying to write some JavaScript code that scales a div element using the transform:scale() CSS property, and then un-scales it so that the element returns to its original size. I thought that if I scale the element by applying transform:scale(a), I could un-scale it by applying transform:scale(1/a), since (element x a) x (1 / a) = element. However, that does not seem to work. Why not?

function scale_up() {
  document.getElementById("div").style.transform = "scale(3)";
}

function scale_down() {
  document.getElementById("div").style.transform = "scale(0.33)";
}

setTimeout(scale_up, 3000)

setTimeout(scale_down, 6000) /* this should return the div to its original size, but it doesn't */
#div {
  height: 30px;
  width: 30px;
  border-style: solid;
}
<body>
  <div id="div"></div>
</body>

CodePudding user response:

CSS is a declarative language, and thus applying new properties on a given element or selector replaces existing ones with the same property name; propierties are not added or multiplied when you set them again.

CSS transforms, building upon this, work the same way: setting the transform to scale(3) and then setting it to scale(0.33) has the same effect as just setting it to scale(0.33): the latter transform replaces the former.

Applying this principle, to undo the transform you can simply remove the CSS property that applies it to your element; you can do this by simply setting the property to an empty string, as per this StackOverflow answer. Alternatively, in this case, you can simply set a scale of 1:

function scale_up() {
  document.getElementById("div").style.transform = "scale(3)";
}

function scale_down() {
  document.getElementById("div").style.transform = "";

  // This would also work:
  //document.getElementById("div").style.transform = "scale(1)";
}

setTimeout(scale_up, 3000)

setTimeout(scale_down, 6000)
#div {
  height: 30px;
  width: 30px;
  border-style: solid;
}
<body>
  <div id="div"></div>
</body>

CodePudding user response:

Applying a css rule doesn't add up, it replace each other.

So first, your scale_up apply a transform: scale(3), your element is scaled x3 from his original size. Then your scale_down apply a transform: scale(0.33), your element is scaled /3 from his original size.

To set it back as normal, apply a transform: scale(1);

CodePudding user response:

scale doesn't apply any permanent effects, you only need to revert to the default scale (100%):

document.getElementById("div").style.transform = "scale(1)";
  • Related