Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

249
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda