Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
How to maintain position after changing div transform-origin?

Let's say I had the following code:

function rotate() {
  const elem = document.querySelector(".rect");

  elem.style.transformOrigin = "top right";
}
.rect {
  width: 200px;
  height: 100px;
  transform: rotateZ(45deg);
  background-color: #ddd;
  transform-origin: center;
}
<div class="rect"></div>

<button onclick="rotate()">Rotate</button>

You'll notice that when you click the Rotate button that the rectangle's transform-origin property changes from center to top right. As a result, the rectangle moves, because it is now rotated around a different origin.

Is it possible to have the rectangle maintain its current position, even after changing the transform origin? I am looking for a way to be able to change an element's transform origin while having it not move at all afterwards.

Basically, I'm looking for a way such that I can change the transform origin, but the div would be visually unchanged. I assume this involves some sort of translation in the rotate Javascript function, but I'm unsure of the exact calculations required to achieve such an effect.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The following seems to work:

function setRectangleOrigin(elem, newOrigin) {
  const compStyle = window.getComputedStyle(elem);

  const prevML = parseInt(compStyle.marginLeft);
  const prevMT = parseInt(compStyle.marginTop);

  const r1 = elem.getBoundingClientRect();
  elem.style.transformOrigin = newOrigin;
  const r2 = elem.getBoundingClientRect();

  elem.style.marginLeft = prevML + (r1.x - r2.x);
  elem.style.marginTop = prevMT + (r1.y - r2.y);
}

Call it like this:

setRectangleOrigin(document.querySelector(".elem"), "top left");

It takes the margin left and margin top of the current rectangle and then calculates its bounding client rect. It then applies the change to the transformation origin and then immediately gets the new bounding client rect.

Then it's a matter of simply transforming the margin left via the change in position.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!